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
declarefunctionunbox<T>(box: {value: T|undefined}): T;declareconstsu: string|undefined;constb1={value: su?.length};// Incorrect error - T inferred to be number | undefinedconstv1: number=unbox(b1);// No errorconstb2={value: su?.lengthasnumber|undefined};constv2: number=unbox(b2);// No errorconstb3: {value: number|undefined}={value: su?.length};constv3: number=unbox(b3);
Expected behavior: In all cases, T should be inferred to be number
Actual behavior: When the undefined part of the union of the type of value originates in an optional chaining, it doesn't infer correctly
I think I've come across the same issue. This is my code:
letvalues={a: 1}as{a: number}|undefined;leta=values?.a;assertDefined(a);// This does not narrow the type to numberconsole.log(a.toString());// Error: Object is possibly undefinedfunctionassertDefined<T>(x: T|undefined|null): asserts x is T{if(x==null){thrownewError('Expected a value');}}
TypeScript Version: 10/18/2019 nightly
Search Terms: optional chaining generic inference undefined
Code
Expected behavior: In all cases,
T
should be inferred to benumber
Actual behavior: When the
undefined
part of the union of the type ofvalue
originates in an optional chaining, it doesn't infer correctlyPlayground Link: http://www.typescriptlang.org/play/?ts=Nightly&ssl=1&ssc=1&pln=15&pc=1#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXzQCMcAPAHgBUA+ACmJIC54BveANygmRCYvgB8CqUIiyoQweAF8AlLwDcAWABQoSLARg8AZwzxtyJrphiA5gKEixEpcpVbUu+IQCM8ALwt2nbkeQB+ADoIEFRTDAALaVsAehj4AEl0HBg4THgQVJT4AFp4PjFETLhJDBxnBFRkAFtCTIs0K3Fgex09NhcmKtr6zyJSOhcZWxU4+AA5cuKU1sc9QgAmDy8OLh59AODQ8KiobXhuupgG4RBRZujZpzYFrpqj5f6SOgXhlVH4yYysmCv5gGYmKxVr4Dvd6oJGmdrJIpMtgT51gYgiEwpF4JdlA5roCwT1jn1UPQ6P83sogA (nightly link)
Related Issues: Nope
The text was updated successfully, but these errors were encountered: