Given the following state:
type DataType = {
a: string,
b: number,
c: boolean
}
const testObject: DataType = {
a: 'Dummy',
b: 1,
c: true
}
type A = typeof testObject['a'] // string
type B = typeof testObject['b'] // number
type C = typeof testObject['c'] // boolean
It is clear that I can get the type of each property of the DataType
object by using either typeof testObject['a']
or DataType['a']
.
However, when I try to do the same via accessor inside a function, I cannot get the exact type of the property I am accessing. Example below:
function testAccess<T>(o: T, p: keyof T): T[typeof p] {
return o[p]
}
const a = testAccess(testObject, 'a') // string | number | boolean
Am I missing something, and is there any way to narrow down the type to the exact key that we are sending?
TS playground link: https://www.typescriptlang.org/play?jsx=0#code/C4TwD...
CodePudding user response:
The trick is to include the key type as a generic parameter:
function testAccess<T, P extends keyof T>(o: T, p: P): T[P] {
return o[p]
}
const a = testAccess(testObject, 'a') // string