我有一个像这样的常量对象
const rack = {
topShelf: {
colors: ["red", "green"],
},
middleShelf: {
colors: ["yellow", "blue"],
},
bottomShelf: {
colors: ["orange", "purple"],
},
}
我想创建一个联合类型,如:
type Color = "red" | "green" | "yellow" | "blue" | "orange" | "purple"
机架对象只是一个例子。在实际应用中,对象有大约 30 个字段。
我知道如何手动完成
type Color =
| typeof rack["topShelf"]["colors"][number]
| typeof rack["middleShelf"]["colors"][number]
| typeof rack["bottomShelf"]["colors"][number]
但它容易出错,我确信有一种方法可以让 Typescript 推断出这种联合类型。
对的,这是可能的。
const rack = {
topShelf: {
colors: ["red", "green"],
},
middleShelf: {
colors: ["yellow", "blue"],
},
bottomShelf: {
colors: ["orange", "purple"],
},
extraDeepNestedProperty: {
nestedProperty: {
colors: ['rgb']
}
}
} as const
type Rack = typeof rack
type IsNever<T> = [T] extends [never] ? true : false
type Union<T, Cache extends string = never> =
IsNever<keyof T> extends true
? Cache
: {
[Prop in keyof T]:
T[Prop] extends ReadonlyArray<string>
? Cache | T[Prop][number]
: Union<T[Prop], Cache>
}[keyof T]
type Result = Union<Rack>
对待Cache
一个记忆化。
Union
是递归类型。
Playground我制作了通用解决方案,它不仅适用于 2 级嵌套,
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句