标题已经说明了一切,但最好用一个例子来解释。
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
然而,这允许使用接口A
的任何keyof
。(即上述两个调用都是有效的)。
在typescript中是否有可能实现这一点?