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
Runtime type-checking fails for other values of same type
Code
transform<T>(items: T[],orderKey: string,reverse?: boolean): T[]{items.sort((a,b)=>{constfirstVal=findNested<T>(reverse ? b : a,orderKey);//findNested returns Tif(firstVal==null)return0;constsecondVal=findNested<T>(reverse ? a : b,orderKey);if(typeoffirstVal==="string"){returnthis.stringCompare(firstVal,secondVal);// ERROR, compiler doesn't know if secondVal is string}}
Expected behavior:
Compiler knows both values are T and therefor after typechecking one value, the other value is of the same expected type as the checked value. Actual behavior:
Even though both values are of type T, not both values are of the same type anymore after type check.
The text was updated successfully, but these errors were encountered:
No, as my example shows this assumption is not valid. Subtyping lets you widen the type of a container so that it could contain values that do not behave uniformly under typeof, or some other predicate.
While I expect that in most cases the intent would be for every value to be a string, it's not true in general and it would be incorrect to behave as if it were. Unfortunately, TypeScript currently has no facility to take that intent and allow a user to explicitly indicate it in the type. That is part of my proposal in #28430.
typescript@next ~ vscode plugin
Runtime type-checking fails for other values of same type
Code
Expected behavior:
Compiler knows both values are T and therefor after typechecking one value, the other value is of the same expected type as the checked value.
Actual behavior:
Even though both values are of type T, not both values are of the same type anymore after type check.
The text was updated successfully, but these errors were encountered: