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

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

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

问题

  1. type KeysToValues<T, K> = any
  2. type A = KeysToValues<{a: number, b: string}, ['a', 'b']>
  3. // [number, string]
  1. type KeysToValues<O extends Record<string, any>, K> = K extends [
  2. infer G,
  3. ...infer L
  4. ]
  5. ? G extends keyof O
  6. ? L extends (keyof O)[]
  7. ? [O[G], ...KeysToValues<O, L>]
  8. : O[G]
  9. : any
  10. : any
  11. type A = KeysToValues<{ a: string }, ['a']>
  12. // [string, ...any[]]
英文:

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

  1. type KeysToValues&lt;T, K&gt; = any
  2. type A = KeysToValues&lt;{a: number, b: string}, [&#39;a&#39;, &#39;b&#39;]&gt;
  3. // [number, string]

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

  1. type KeysToValues&lt;O extends Record&lt;string, any&gt;, K&gt; = K extends [
  2. infer G,
  3. ...infer L
  4. ]
  5. ? G extends keyof O
  6. ? L extends (keyof O)[]
  7. ? [O[G], ...KeysToValues&lt;O, L&gt;]
  8. : O[G]
  9. : any
  10. : any
  11. type A = KeysToValues&lt;{ a: string }, [&#39;a&#39;]&gt;
  12. // [string, ...any[]]

答案1

得分: 1

你之前的做法是正确的,但是它在列表中显示了 any,因为在某个地方你返回了 any。只需将你的 any 改成 [],这样一个空数组就会连接到结果中:

  1. type KeysToValues<O extends Record<string, any>, K> = K extends [
  2. infer G,
  3. ...infer L
  4. ]
  5. ? G extends keyof O
  6. ? L extends (keyof O)[]
  7. ? [O[G], ...KeysToValues<O, L>]
  8. : O[G]
  9. : []
  10. : []
  11. type A = KeysToValues<{ a: string, b: number, c: boolean }, ['a', 'c']>
  12. // [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:

  1. type KeysToValues&lt;O extends Record&lt;string, any&gt;, K&gt; = K extends [
  2. infer G,
  3. ...infer L
  4. ]
  5. ? G extends keyof O
  6. ? L extends (keyof O)[]
  7. ? [O[G], ...KeysToValues&lt;O, L&gt;]
  8. : O[G]
  9. : []
  10. : []
  11. type A = KeysToValues&lt;{ a: string, b: number, c: boolean }, [&#39;a&#39;, &#39;c&#39;]&gt;
  12. // [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:

确定