【发布时间】:2021-10-05 20:30:20
【问题描述】:
给定以下状态:
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
很明显,我可以使用typeof testObject['a'] 或DataType['a'] 来获取DataType 对象的每个属性的类型。
但是, 当我尝试通过函数内部的访问器执行相同操作时,我无法获得我正在访问的属性的确切类型。下面的例子:
function testAccess<T>(o: T, p: keyof T): T[typeof p] {
return o[p]
}
const a = testAccess(testObject, 'a') // string | number | boolean
我是否遗漏了什么,有什么方法可以将类型缩小到我们发送的确切密钥?
TS 游乐场链接:https://www.typescriptlang.org/play?jsx=0#code/C4TwD...
【问题讨论】:
标签: typescript typescript-generics