【问题标题】:Get all keys of specific type from object in typescript [duplicate]从打字稿中的对象获取特定类型的所有键[重复]
【发布时间】:2021-01-22 23:54:45
【问题描述】:

标题说明了一切,但最好举个例子。

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

可以用打字稿来做到这一点吗?

【问题讨论】:

标签: typescript


【解决方案1】:

将您的 KeysofType 定义更改为:

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

这在this post中有详细解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-27
    • 2020-08-12
    • 2021-12-24
    • 2019-03-13
    • 2019-01-02
    • 2022-01-12
    • 1970-01-01
    • 2021-03-19
    相关资源
    最近更新 更多