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
typeSelection={multiple: true;value: string[];callback: (_: string[])=>void;}|{multiple: false;value: string;callback: (_: string)=>void;};functiontest(a: Selection){// Error: Typescript does not recognise that `value` and `callback` use the same type.a.callback(a.value);if(a.multiple){// Valid: Typescript narrowed down the type to `string[]`a.callback(a.value);}else{// Valid: Typescript narrowed down the type to `string`a.callback(a.value);}}
π Actual behavior
Typescript does not recognise that callback will always accept value as a parameter, since they both use either string or string[].
Interestingly, Typescript can infer the types properly using the if (multiple) { ... } condition.
π Expected behavior
All three callback(value) calls should be valid, from a type point of view.
Additional information about the issue
No response
The text was updated successfully, but these errors were encountered:
It's probably closed because it has been determined that it would be too computationally expensive to do it and the current best solution is to use the "indexed mapped type as a union" pattern from TS 4.6 (see here).
However, this discriminant value isn't easily used as a property key so while we can make the internal implementation of a function happy about it... it still doesn't quite infer a concrete K that is used and it doesn't discriminate the input argument for contextual parameters etc: TS playground
Using some intersections we can fix the latter: TS playground. It still doesn't infer K though and I'm not sure how to make true/false a viable inference source for "true"/"false"
π Search Terms
"inference" "inference narrow" "inference discriminant" "inference union"
π Version & Regression Information
Tested on multiple versions, this is not a new bug.
β― Playground Link
https://www.typescriptlang.org/play?ts=5.4.2#code/C4TwDgpgBA6gTgewHYHMCSSBmE4SQY2gF4oBvAKAEgBbAVwBtgBLMeiALimDlogG4qANwCG9XpwDO3JqgDaAXQGV8o+gCNh+ANacAFAH1J0ufICUUIgD4oghEwAmAgL5QAPmSp1GLNp0yiJfiFRcSgpOBkUJRV6dU0dKAMjCNRzKxs7R3InAXJMWgJmZCg2YABVCQxsOF1hTnhkdCwcPEJzCkphADoYuO1arpExCFMlJkxE7q9mVhGPSk6e1Q1+7qHeUaoXCHpA+cXela0B9ZGlJ2zyIA
π» Code
π Actual behavior
Typescript does not recognise that
callback
will always acceptvalue
as a parameter, since they both use eitherstring
orstring[]
.Interestingly, Typescript can infer the types properly using the
if (multiple) { ... }
condition.π Expected behavior
All three
callback(value)
calls should be valid, from a type point of view.Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: