TypeScript Version: 3.8.3
Search Terms:
Expected behavior:
TypeScript should infer the type of value when given the key for a concrete type.
Actual behavior:
TypeScript does not infer the type of value when given the key for a concrete type
Related Issues:
Code
type ValueOf<T> = T[keyof T];
type KeyFor<T, V> = ValueOf<{ [K in keyof T]: T[K] extends V ? K : never }>
type Thing = {
a: number;
}
type Reader<T> = {
get: <V>(key: KeyFor<T, V>) => V
}
// when dealing with a generic, TS correctly figures out that the return type is number
function getNumber<T>(reader: Reader<T>, numberKey: KeyFor<T, number>) {
return reader.get(numberKey);
}
declare const thingReader: Reader<Thing>
// when dealing with the concrete type `Thing`, TS inference fails
function getNumberFromMyThing(numberKey: KeyFor<Thing, number>) {
return thingReader.get(numberKey)
}
Output
"use strict";
function getNumber(store, numberKey) {
return store.get(numberKey);
}
function getNumberFromMyThing(numberKey) {
return thingReader.get(numberKey);
}
Compiler Options
{
"compilerOptions": {
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"useDefineForClassFields": false,
"alwaysStrict": true,
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"downlevelIteration": false,
"noEmitHelpers": false,
"noLib": false,
"noStrictGenericChecks": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"esModuleInterop": true,
"preserveConstEnums": false,
"removeComments": false,
"skipLibCheck": false,
"checkJs": false,
"allowJs": false,
"declaration": true,
"experimentalDecorators": false,
"emitDecoratorMetadata": false,
"target": "ES2017",
"module": "ESNext"
}
}
Playground Link: Provided
TypeScript Version: 3.8.3
Search Terms:
Expected behavior:
TypeScript should infer the type of value when given the key for a concrete type.
Actual behavior:
TypeScript does not infer the type of value when given the key for a concrete type
Related Issues:
Code
Output
Compiler Options
{ "compilerOptions": { "noImplicitAny": true, "strictNullChecks": true, "strictFunctionTypes": true, "strictPropertyInitialization": true, "strictBindCallApply": true, "noImplicitThis": true, "noImplicitReturns": true, "useDefineForClassFields": false, "alwaysStrict": true, "allowUnreachableCode": false, "allowUnusedLabels": false, "downlevelIteration": false, "noEmitHelpers": false, "noLib": false, "noStrictGenericChecks": false, "noUnusedLocals": false, "noUnusedParameters": false, "esModuleInterop": true, "preserveConstEnums": false, "removeComments": false, "skipLibCheck": false, "checkJs": false, "allowJs": false, "declaration": true, "experimentalDecorators": false, "emitDecoratorMetadata": false, "target": "ES2017", "module": "ESNext" } }Playground Link: Provided