google / google/closure-compiler

Undefined in typedef causes type mismatches to be silently ignored

Open
#1,150 3 comments 0 reactions 0 assignees View on GitHub
bug Types
Dominant language
JavaScript
Stars
7.7k
Forks
1.2k
Avg merge
2d 12h
Merged PRs (30d)
6

Description

Externs:

``` javascript
/** @typedef {{ sausages: (?string) }} */
var GOOD;

/** @typedef {{ sausages: (string|null|undefined) }} */
var BAD;
```

Code:

``` javascript
/** @param {GOOD} obj */
var testGood = function(obj) {};

/** @param {BAD} obj */
var testBad = function(obj) {};

testGood({bacon: "mmm"}) // correctly fails
testBad({bacon: "yuck"}) // should fail, doesn't
```

It appears changing from `?string` to `string|null|undefined` causes the entire typedef to be disregarded silently.

https://closure-compiler-debugger.appspot.com/#input0%3D%252F**%2520%2540param%2520%257BGOOD%257D%2520obj%2520*%252F%250Avar%2520testGood%2520%253D%2520function(obj)%2520%257B%257D%253B%250A%250A%252F**%2520%2540param%2520%257BBAD%257D%2520obj%2520*%252F%250Avar%2520testBad%2520%253D%2520function(obj)%2520%257B%257D%253B%250A%250AtestGood(%257Bbacon%253A%2520%2522mmm%2522%257D)%2520%252F%252F%2520correctly%2520fails%2520%250AtestBad(%257Bbacon%253A%2520%2522yuck%2522%257D)%2520%252F%252F%2520should%2520fail%252C%2520doesn't%26input1%26conformanceConfig%26externs%3D%252F**%2520%2540typedef%2520%257B%257B%2520%2520sausages%253A%2520(%253Fstring)%2520%2520%257D%257D%2520*%252F%250Avar%2520GOOD%253B%250A%250A%252F**%2520%2540typedef%2520%257B%257B%2520%2520sausages%253A%2520(string%257Cnull%257Cundefined)%2520%257D%257D%2520*%252F%250Avar%2520BAD%253B%26refasterjs-template%26CHECK_SYMBOLS%3D1%26CHECK_TYPES%3D1%26MISSING_PROPERTIES%3D1

Background:
I'm trying to make it easy for a developer to pass a clean and simple JS object literal into a method, and have Closure Compiler verify the object literal matches all expected properties, e.g.:

``` javascript
someFunc({
propA: 5,
propB: ["a", "b"]
// propC optional and missing
});
```

Hence I need to allow for undefined. I was surprised that `?` didn't mean "null or undefined", and think the only way of doing this is using `string|null|undefined` in this example.

This issue is somewhat worrying because it is easy to inadvertently disable all typechecks. Presumably this is a bug. But if this is intended for some reason, it would benefit from some warning that could be turned off, rather than silently ignoring failures.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.