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

huangapple go评论53阅读模式
英文:

Typescript, How to get the value of an object based on its key?

问题

type KeysToValues<T, K> = any

type A = KeysToValues<{a: number, b: string}, ['a', 'b']>
// [number, string]
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[]]
英文:

How do I implement KeysToValues so that I can return the corresponding value based on the second parameter?

type KeysToValues&lt;T, K&gt; = any

type A = KeysToValues&lt;{a: number, b: string}, [&#39;a&#39;, &#39;b&#39;]&gt;
// [number, string]

One more last in my realization... .any[]

type KeysToValues&lt;O extends Record&lt;string, any&gt;, K&gt; = K extends [
  infer G,
  ...infer L
]
  ? G extends keyof O
    ? L extends (keyof O)[]
      ? [O[G], ...KeysToValues&lt;O, L&gt;]
      : O[G]
    : any
  : any

type A = KeysToValues&lt;{ a: string }, [&#39;a&#39;]&gt;
// [string, ...any[]]

答案1

得分: 1

你之前的做法是正确的,但是它在列表中显示了 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]
英文:

You were on the right track, but it shows any in the list because you are returning any at some point. Just change your any to [] so an empty array is concatenated to the result:

type KeysToValues&lt;O extends Record&lt;string, any&gt;, K&gt; = K extends [
  infer G,
  ...infer L
]
  ? G extends keyof O
    ? L extends (keyof O)[]
      ? [O[G], ...KeysToValues&lt;O, L&gt;]
      : O[G]
    : []
  : []

type A = KeysToValues&lt;{ a: string, b: number, c: boolean }, [&#39;a&#39;, &#39;c&#39;]&gt;
// [string, boolean]

huangapple
  • 本文由 发表于 2023年5月22日 15:52:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76304034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定