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
declareletcond: boolean;declarefunctionidentity<T>(x: T): T;declarefunctionwidening<T>(x: T): {prop: T};declarefunctionnonWidening<Textendsstring|number|symbol>(x: T): {prop: T};// this already works in older versionsconstv1=identity('a');// "a"constv2=identity(10);// 10constv3=identity(cond ? 'a' : 10);// "a" | 10// unchangedconstx1=widening('a');// stringconstx2=widening(10);// numberconstx3=widening(cond ? 'a' : 10);// string | number// new in 2.9consty1=nonWidening('a');// "a"consty2=nonWidening(10);// 10consty3=nonWidening(cond ? 'a' : 10);// "a" | 10
Therefore:
identity('a'as'a');// lint error in all typescript versionswidening('a'as'a');// no errornonWidening('a'as'a');// lint error starting from 2.9// also handle these casesidentity(cond ? 'a'as'a' : 10as10);declarefunctionarr<Textendsstring|number>(...params: T[]): T[];arr(1as1,2as2,3as3);
On a related note: I don't really know what the PR above changed. It seems everything already worked as expected before that change ...
The text was updated successfully, but these errors were encountered:
It turns out the PR linked above doesn't really do what I expected.
In fact the rule that applies here is way more simple than described above:
If an expression has a non-widening type, there's no need for an assertion. See microsoft/TypeScript#11126 for an explanation of widening types.
It turns out the type system is not really helpful here. Because getWidenedLiteralType and ts.TypeFlags.FreshLiteral are not exposed, there's no way to know if a type is a non-widening type.
For now this will probably only work for contextual types that are type parameters with a primitive type in their constraint. This also requires #282 to be implemented.
[email protected] no longer widens literal types if the type parameter is constrained with at least one primitive type.
microsoft/TypeScript#24310
Therefore:
On a related note: I don't really know what the PR above changed. It seems everything already worked as expected before that change ...
The text was updated successfully, but these errors were encountered: