I'm trying to get the type of an property from within a generic type:
export type TestType = {
key1: string,
key2: number,
key3: Array<string>
};
const test:TestType = {
key1: 'hello',
key2: 56,
key3: ['hi']
};
function getProperty<T> (obj:T, property:keyof T): T[typeof property]{
return obj[property];
}
const thisVariableShouldBeAString:string = getProperty<TestType>(test, 'key1');
//thisVariableShouldBeAString has type "string | number | string[]" which is not "string"
But it does not work! thisVariableShouldBeAString ends up with an union types of all the properties within TestType
Doing test['key1']
instead of getProperty<TestType>(test, 'key1')
is not sufficient for my usecase.
Is it possible to properly type the getProperty function?
CodePudding user response:
You can add another type parameter to getProperty
that extends keyof T
:
export type TestType = {
key1: string,
key2: number,
key3: Array<string>
};
const test: TestType = {
key1: 'hello',
key2: 56,
key3: ['hi']
};
function getProperty<T, K extends keyof T>(obj: T, property: K): T[K] {
return obj[property];
}
const thisVariableShouldBeAString = getProperty(test, 'key1');