[英]Use typescript to create union object of keys in objects
I have the following object:我有以下 object:
const myObject = {
one: {
fixed: {
a: 1
}
},
two: {
fixed: {
b: true
}
},
three: {
fixed: {
c: 'foo'
}
}
}
How can I use this object, to create a type equivalent to the following:如何使用此 object 创建与以下内容等效的类型:
type MyUnionType = {
a: number
b: boolean
c: string
}
? ?
You can use您可以使用
type MyObject = typeof myObject;
type MyUnionType = {
[T in keyof MyObject as keyof MyObject[T]["fixed"]]: MyObject[T]["fixed"][keyof MyObject[T]["fixed"]]
}
From the varying top level properties as a type parameter (eg ( one
), it first extracts the key of the nested object (eg a
or b
) and then (verbosely) accesses the nested value associated with that key.从不同的顶级属性作为类型参数(例如(
one
),它首先提取嵌套 object 的键(例如a
或b
),然后(详细地)访问与该键关联的嵌套值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.