google / google/closure-compiler

Default function parameters typed as undefined when enclosed in an internal function

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

Description

I think this looks like a bug in the compiler, see the minimal test case below.

The function parameter has a default, so it may never be "undefined" and the compiler honours this.

What I didn't expect is that enclosed in a function it somehow it picks up the possibility to be "undefined".

It happens for a range of types; function, string etc. The case where I noticed was a callback function provided to a constructor.

If I'm mistaken and this is not a bug but actually some edge case of the language then I'd also be open to hear of that. Many thanks.

```
/**
* @param {string} v
*/

function outer(v = 'fallback') {
inner(v); // <-- string

function local() {
inner(v); // <-- string|undefined ???
}
}

/**
* @param {string} v
*/

function inner(v) {
console.log(v);
}

outer();
```

```
$ java -jar closure-compiler-v20230502.jar -O ADVANCED test.js
test.js:9:14: WARNING - [JSC_TYPE_MISMATCH] actual parameter 1 of inner does not match formal parameter
found : (string|undefined)
required: string
9| inner(v);
^

0 error(s), 1 warning(s), 100.0% typed
(function(a="fallback"){console.log(a)})();
```

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.