[英]Unwrap Object Type recursively in TypeScript
I want to unwrap some types in TypeScript, here is example:我想在 TypeScript 中解开一些类型,这里是例子:
// previously defined Type<T>
// example of wrapped type:
type Wrapped = Type<{
a: Type<boolean>,
b: Type<{
c: Type<number>
}>
}>
type Unwrap = ...// this needs to be defined
//And its usage like:
type Unwrapped1 = Unwrap<Wrapped>// should be: { a: boolean, b: { c: number } }
type Unwrapped2 = Unwrap<Type<string>>// should be: string
.
.
.
How Unwrap can be defined?如何定义Unwrap ?
You can use mapped and conditional types and mapped types to unwrap the type:您可以使用映射和条件类型以及映射类型来解包类型:
type UnwrapObject<T> = {
[P in keyof T] : Unwrap<T[P]>
}
type Unwrap<T> = T extends Type<infer U> ?
U extends object ? UnwrapObject<U> : U:
T extends object ? UnwrapObject<T> : T
//And its usage like:
type Unwrapped1 = Unwrap<Wrapped>// should be: { a: boolean, b: { c: number } }
type Unwrapped2 = Unwrap<Type<string>>// should be: string
declare let d: Unwrapped1;
d.b.c // number
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.