在TypeScript中从对象中获取特定类型的所有键

6

标题已经说明了一切,但最好用一个例子来解释。

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中是否有可能实现这一点?


简而言之,是的,你的答案是正确的。然而,我希望在函数内部也能够工作(即,obj[key]将被推断为类型T),但实际上并不是这样。我可以理解为什么这不可能或者还没有得到支持,因为它有点复杂。类型系统需要知道“key”只会从类型为“T”的“obj”中提取值。 - HelloWorld
1个回答

16

将您的KeysofType定义更改为:

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

这在这篇文章中有详细解释。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接