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
typeA={s: string;n: number;};// K here may be 's'|'n' or 's' or 'n' (but not never as I understand, as f cannot accept argument of type never in runtime)functionf<KextendskeyofA>(key: K): A[K]{constk1: typeofkey='s';// It is completely fine for this line to have an error (as it is outside if check and K may be 'n')if(key==='s'){// In fact we know that type of x === 's' here.// Thus return type here should be A['s'] in other words it should be a string// But TypeScript still thinks it is of type A[K]constk2: typeofkey='s';// does not work. Here I expect typeof key to be 's'constc: A[K]='test';// does not work. Here I expect A[k] to be stringconstd: A['s']='test';// worksreturn'test';// does not work. Here I expect 'test' to be asignable to A[K]}if(key==='n'){return10;// the same}thrownewError();}
π Actual behavior
Typescript ignores the check on the variable typed with a subtype of union type and is unable to narrow type
Bug Report
π Search Terms
discriminated type union, narrowing, generics
π Version & Regression Information
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
Typescript ignores the check on the variable typed with a subtype of union type and is unable to narrow type
π Expected behavior
Typescript narrows the type
My guess is that this behavior may somehow be related to https://devblogs.microsoft.com/typescript/announcing-typescript-3-5/#fixes-to-unsound-writes-to-indexed-access-types
The text was updated successfully, but these errors were encountered: