I have encountered an issue which basically involves narrowing the type returned from an object, accessed by its key. Let's say I have this an object whose values can be either number
or string
:
type Value = number | string;
enum DatumKey {
numberDatum = 'numberDatum',
stringDatum = 'stringDatum',
}
class DemoClass {
private data = {
[DatumKey.numberDatum]: 1337,
[DatumKey.stringDatum]: 'foobar',
}
public getValue(key: DatumKey): Value {
return this.data[key];
}
public doSomething(): void {
const num: number = this.getValue(DatumKey.numberDatum); // TS expects `number | string`, I expect `number`
const str: string = this.getValue(DatumKey.stringDatum); // TS expects `number | string`, I expect `string`
console.log({ num, str });
}
}
const dc = new DemoClass();
dc.doSomething();
See Typescript Playground example.
So, in order to narrow the type, I have attempted to use a generic type, and I can then tell getValue<...>()
what kind of type am I expecting in return:
public getValue<T extends Value>(key: DatumKey): T {
// Error here: Type 'Value' not assignable to type 'T'
return this.data[key];
}
public doSomething(): void {
const num: number = this.getValue<number>(DatumKey.numberDatum); // TS expects `number`, it's good!
const str: string = this.getValue<string>(DatumKey.stringDatum); // TS expects `string`, it's good!
}
However, by doing so, I get an error from TypeScript:
Type 'Value' is not assignable to type 'T'.
'Value' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.
Type 'string' is not assignable to type 'T'.
'string' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.
See Typescript Playground example.
Then I came across a similar question here, which suggested that the use of function overloads to fix the issue. It does. However, I am not sure why does a function overload fix the issue:
public getValue<T extends Value>(key: DatumKey): T
public getValue(key: DatumKey): Value {
return this.data[key];
}
public doSomething(): void {
const num = this.getValue<number>(DatumKey.numberDatum); // TS expects `number`, it's good!
const str = this.getValue<string>(DatumKey.stringDatum); // TS expects `string`, it's good!
}
Your working solution does not really works. Variables num
and str
are typed as Value
not as respectively number
and string
.
A more robust solution:
enum DatumKey {
numberDatum = 'numberDatum',
stringDatum = 'stringDatum',
}
const data = {
[DatumKey.numberDatum]: 1337,
[DatumKey.stringDatum]: 'foobar',
};
function getValue<T extends keyof typeof data>(key: T): (typeof data)[T] {
return data[key];
}
// You don't have to explicitly type num and str. They are automatically inferred
const num = getValue(DatumKey.numberDatum);
const str = getValue(DatumKey.stringDatum);