Skip to content

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

Closed

Description

@jcalz

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

Metadata

Metadata

Labels

Bug

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions