Typescript,如何根据对象的键获取对象的值?

oalqel3c  于 2023-05-23  发布在  TypeScript
关注(0)|答案(1)|浏览(216)

如何实现KeysToValues,以便可以根据第二个参数返回相应的值?

type KeysToValues<T, K> = any

type A = KeysToValues<{a: number, b: string}, ['a', 'b']>
// [number, string]

最后一个我意识到的是....any[]

type KeysToValues<O extends Record<string, any>, K> = K extends [
  infer G,
  ...infer L
]
  ? G extends keyof O
    ? L extends (keyof O)[]
      ? [O[G], ...KeysToValues<O, L>]
      : O[G]
    : any
  : any

type A = KeysToValues<{ a: string }, ['a']>
// [string, ...any[]]
aemubtdh

aemubtdh1#

您的思路是正确的,但它在列表中显示了any,因为您在某个时候返回了any。只需将any更改为[],以便将空数组连接到结果:

type KeysToValues<O extends Record<string, any>, K> = K extends [
  infer G,
  ...infer L
]
  ? G extends keyof O
    ? L extends (keyof O)[]
      ? [O[G], ...KeysToValues<O, L>]
      : O[G]
    : []
  : []

type A = KeysToValues<{ a: string, b: number, c: boolean }, ['a', 'c']>
// [string, boolean]

相关问题