admin管理员组文章数量:1125904
const obj = [
{
key: 'fruit',
value: ['apple', 'banana']
},
{
key: 'meat',
value: ['pork', 'chicken']
}
] as const;
I want to generate type
type T = {
'fruit': 'apple' | 'banana',
'meat': 'pork' | 'chicken'
}
I searched but I can't find how to use value as a key. How can I generate type from the object?
const obj = [
{
key: 'fruit',
value: ['apple', 'banana']
},
{
key: 'meat',
value: ['pork', 'chicken']
}
] as const;
I want to generate type
type T = {
'fruit': 'apple' | 'banana',
'meat': 'pork' | 'chicken'
}
I searched but I can't find how to use value as a key. How can I generate type from the object?
Share Improve this question asked Jan 9 at 2:03 kkh.namekkh.name 154 bronze badges 1- Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Bot Commented Jan 9 at 2:44
1 Answer
Reset to default 2Yes, you can use a mapped type with key remapping to iterate over the members of the union corresponding to the element type of the obj
array, and map the "key"
property to the key and the element type of the "value"
property to the value:
type Tee = { [O in typeof obj[number] as O["key"]]: O["value"][number] }
/* type Tee = {
fruit: "apple" | "banana";
meat: "pork" | "chicken";
} */
Note that you need the typeof
type operator to get the type of the obj
value, and you need indexed access types to get the type of a value at a particular type of key. So if O
is an object with key
and value
properties, then O["key"]
is the type of the key
property and O["value"]
is the type of the value
property. And for arrays, indexing with number
(e.g., (typeof obj)[number]
or (O["value"])[number]
) gives you the element type (or a union of them, if it is a heterogeneous array).
Playground link to code
本文标签: mapped typesIs there way to declare using the value as a key in typescriptStack Overflow
版权声明:本文标题:mapped types - Is there way to declare using the value as a key in typescript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736678160a1947289.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论