标题说明了一切,但最好举个例子。
interface A {
key1: string
key2: string
key3: number
}
type KeysOfType<O, T> = keyof {
[K in keyof O]: O[K] extends T ? O[K] : never
}
function test<O,T>(obj: O, key: KeysOfType<O,T>) {
obj[key] // should only be of type T
}
const aa: A = {
key1: "1",
key2: "2",
key3: 3
}
test<A,string>(aa, "key1") // should be allowed, because key1 should be a string
test<A,string>(aa, "key3") // should NOT be allowed (but is), because key3 should be a number
然而,这允许任何keyof
界面A
。 (即,上面的两个调用都是有效的)。
可以用打字稿做到这一点吗?
将 KeysofType 定义更改为:
type KeysOfType<O, T> = {
[K in keyof O]: O[K] extends T ? K : never
}[keyof O]
这在中详细解释了这个帖子 https://stackoverflow.com/questions/51419176/how-to-get-a-subset-of-keyof-t-whose-value-tk-are-callable-functions-in-typ.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)