Reputation: 270
I tried like below to returns various types depends on input string key, but it doesn't works.
How to make the getSpecificData
functions to return type I want?
type Data = {
foo: string;
bar: number;
baz: boolean;
};
function getSpecificData<D>(data: D, dataKey: keyof D): D[keyof D] {
return data[dataKey];
}
const sampleData: Data = {
foo: 'hello',
bar: 123,
baz: false,
};
const foo: string = getSpecificData(sampleData, 'foo'); // the function returns string|number|boolean
const bar: number = getSpecificData(sampleData, 'bar');
const baz: boolean = getSpecificData(sampleData, 'baz');
Upvotes: 0
Views: 308
Reputation: 42298
Both the key and the value need to be generic in order to get the value type for the specific key that you provided. D[keyof D]
is a union of all possible value types, but D[K]
will give us the correct value for a given key K
.
function getSpecificData<D, K extends keyof D>(data: D, dataKey: K): D[K] {
return data[dataKey];
}
This allows Typescript to return the specific value type associated with the provided key. Now all of these examples work:
const foo: string = getSpecificData(sampleData, 'foo');
const bar: number = getSpecificData(sampleData, 'bar');
const baz: boolean = getSpecificData(sampleData, 'baz');
Upvotes: 1