You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Opened from SO question since this seems like a possible bug.
TypeScript supports using an explicit undefined for the value of an optional discriminant and contextual typing works with that, but contextual typing does not fully work when an optional discriminant is missing.
Code
interfaceNumProps{isString?: falseonChange: (value: number)=>void}interfaceStringProps{isString: true,onChange: (value: string)=>void}typeProps=NumProps|StringPropsconstprops: Props={// Error: Parameter 'value' implicitly has an 'any' type.// Expected: 'value' is contextually typed as 'number'.onChange: value=>{},}constpropsUndefined: Props={isString: undefined,// OK: 'value' is contextually typed as 'number'. onChange: value=>{},}
Expected behavior:value is contextually typed as number for props
As pointed out in the SO comments, annotating value with an invalid type will error which suggests that TS is correctly resolving the discriminated union, but possibly not applying contextual typing to onChange at the right time.
constprops: Props={// Error: Type 'number' is not assignable to type 'boolean'.onChange: (value: boolean)=>{}}
Related Issues: #16817 #13195 (Missing vs undefined props)
The text was updated successfully, but these errors were encountered:
matt-tingen
changed the title
Contextual typing with Optional discriminant differs from optional discriminant
Contextual typing with optional discriminant
May 28, 2019
It seems to be working on the TS playground now. The type of value is inferred correctly. However, if you add an optional property on B, and you add that property to props, there is no error which I think is incorrect.
TypeScript Version: 3.5.0-dev.20190525
Search Terms: discriminated union, optional discriminant, contextual typing, missing vs undefined
Opened from SO question since this seems like a possible bug.
TypeScript supports using an explicit
undefined
for the value of an optional discriminant and contextual typing works with that, but contextual typing does not fully work when an optional discriminant is missing.Code
Expected behavior:
value
is contextually typed asnumber
forprops
Actual behavior:
value
isany
Playground Link: Playground (enable strict options)
As pointed out in the SO comments, annotating
value
with an invalid type will error which suggests that TS is correctly resolving the discriminated union, but possibly not applying contextual typing toonChange
at the right time.Related Issues:
#16817
#13195 (Missing vs undefined props)
The text was updated successfully, but these errors were encountered: