Skip to content

Function with optional destructured parameter not seen as compatible with its inferred type #37271

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
jcalz opened this issue Mar 7, 2020 · 0 comments · Fixed by #37309
Closed
Assignees
Labels
Bug A bug in TypeScript

Comments

@jcalz
Copy link
Contributor

jcalz commented Mar 7, 2020

TypeScript Version: 3.9.0-dev.20200306

Search Terms: annotation, default, optional, destructuring

Code

const fInferred = ({ a = 0 } = {}) => a;
// const fInferred: ({ a }?: { a?: number; }) => number

const fAnnotated: typeof fInferred = ({ a = 0 } = {}) => a; // error!
//  ----------------------------------> ~
// 'a' does not exist on type '{ a?: number | undefined; } | undefined'

const fAnnotationIntensifies: typeof fInferred =
  ({ a = 0 }: { a?: number } = {}) => a; // no error now

Expected behavior:
No error assigning to fAnnotated. The arrow function's parameter should be compatible with the contextual type, since this contextual type comes from the parameter type of fInferred with identical JS code.

Actual behavior:
The destructured parameter a of fAnnotated generates a warning. It is no longer inferred as an optional parameter. You can work around this by explicitly annotating the parameter as in fAnnotationIntensifies but it's not clear why this should be necessary.

This issue came up in this Stack Overflow question where the person wants to explicitly annotate things with their inferred types. It would be nice to know if the behavior here is somehow intentional or correct, or if it's a bug or limitation.

Playground Link: Provided

Related Issues:
#35160 is quite similar but is missing the part where the compiler infers the unannotated function to be of the type annotated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript
Projects
None yet
3 participants