英文:
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<T, K> = any
type A = KeysToValues<{a: number, b: string}, ['a', 'b']>
// [number, string]
One more last in my realization... .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[]]
答案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<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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论