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
enumSwitch{A='a',B='b',}interfaceResultA{keyA1: number;keyA2: string;}typeResultB=number[];typeResultType=ResultA|ResultB;interfaceGenericBase{switch: Switch;value: ResultType;}interfaceGenericAextendsGenericBase{switch: Switch.A;value: ResultA;}interfaceGenericBextendsGenericBase{switch: Switch.B;value: ResultB;}typeGenericType=GenericA|GenericB;functiongetValue<TextendsGenericType,KextendskeyofT['value']>(result: T,key: K): T['value'][K]{// T = GenericA// T['value'] = ResultA// keyof ResultA = 'keyA1' | 'keyA2'// T = GenericB// T['value'] = ResultB// keyof ResultB = number | "toString" | [...]// unexpected: error TS2536: Type 'K' cannot be used to index type 'ResultType'.returnresult.value[key];}consta: GenericA={switch: Switch.A,value: {keyA1: 1,keyA2: 'A'}};constb: GenericB={switch: Switch.B,value: [1,2,3]};// no errorsconsole.log(getValue(a,'keyA1'));console.log(getValue(a,'keyA2'));console.log(getValue(b,0));console.log(getValue(b,3));// error TS2345: Argument of type '0' is not assignable to parameter of type '"keyA1" | "keyA2"'.// => expected, and the compiler does know what keys can be usedconsole.log(getValue(a,0));// error TS2345: Argument of type '"keyA1"' is not assignable to parameter of type 'number | "toString" [...]// => also expectedconsole.log(getValue(b,'keyA1'));
Expected behavior:
As long as the correct keys are used, which is covered by TS2345, the index access should not raise an error.
Actual behavior:
TS2536 is thrown when compiling, altough the keys should be known due to the generic typing.
Uh oh!
There was an error while loading. Please reload this page.
TypeScript Version: 3.8.0-dev.20200204
Search Terms:
Code
Expected behavior:
As long as the correct keys are used, which is covered by TS2345, the index access should not raise an error.
Actual behavior:
TS2536 is thrown when compiling, altough the keys should be known due to the generic typing.
Playground Link: typescriptlang.org
Related Issues:
keyof
if index value type isunknown
#33521The text was updated successfully, but these errors were encountered: