Inconsistencies in type checking functions with optional destructured parameters
See original GitHub issueI encountered unexpected and inconsistent errors when attempting to write a function declaration for a function with an optional destructured parameter with default property values when using strictNullChecks
.
It’s possible that I wrote my function declaration incorrect but I couldn’t find a good example for writing function declarations with an optional destructured parameter with default property values. Regardless, the inconsistency in behavior described in this issue is still a bug AFAICT.
TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)
Code Bug demo (enable strictNullChecks to see error): https://www.typescriptlang.org/play/#src=const want %3D ({a %3D 1%2C b %3D 2} %3D {}) %3D> {}%3B want()%3B want({})%3B want({a%3A 3})%3B want({a%3A 3%2C b%3A 4})%3B want({b%3A 5})%3B let have%3A (nums%3F%3A {a%3F%3Anumber%2C b%3F%3Anumber}) %3D> void%3B have %3D want%3B have %3D ({a %3D 1%2C b %3D 2} %3D {}) %3D> {}%3B %2F%2F Same value as want. have()%3B have({})%3B have({a%3A 3})%3B have({a%3A 3%2C b%3A 4})%3B have({b%3A 5})%3B
let have: (nums?: {a?:number, b?:number}) => void;
have = ({a = 1, b = 2} = {}) => {}; // A. Results in error.
const want = ({a = 1, b = 2} = {}) => {};
have = want; // B. This works fine.
Expected behavior: The lines denoted by A. and B. both work (preferable). OR The lines denoted by A. and B. fail in the same way.
Actual behavior: The line denoted by A. results in errors:
Type '{ a?: number | undefined; b?: number | undefined; } | undefined' has no property 'a' and no string index signature.
Type '{ a?: number | undefined; b?: number | undefined; } | undefined' has no property 'b' and no string index signature.
The line denoted by B. works.
Issue Analytics
- State:
- Created 6 years ago
- Comments:7 (5 by maintainers)
In the meantime, both bugs can be worked around by adding an explicit type annotation to the destructured parameter itself:
const want = ({ a = 1, b = 2 }: { a?: number, b?: number} = {}) => {};
PR is out! 😃