从打字稿中的对象获取特定类型的所有键

时间:2020-10-08 00:09:09

标签: typescript

标题说明了一切,但最好的例子是

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。 (即,上述两个调用均有效)。

有可能用打字稿做到这一点吗?

1 个答案:

答案 0 :(得分:2)

将您的KeysofType定义更改为:

type KeysOfType<O, T> = {
  [K in keyof O]: O[K] extends T ? K : never
}[keyof O]

这在this post中有详细说明。