在TypeScript中递归展开对象类型

在TypeScript中递归展开对象类型,typescript,typescript-generics,Typescript,Typescript Generics,我想在TypeScript中展开一些类型,以下是示例: // previously defined Type<T> // example of wrapped type: type Wrapped = Type<{ a: Type<boolean>, b: Type<{ c: Type<number> }> }> type Unwrap =

我想在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
    .
    .
    .
//以前定义的类型
//包装类型的示例:
类型=类型
类型Unwrap=…//这需要定义
//其用法如下:
类型unwrappd1=Unwrap//应为:{a:boolean,b:{c:number}
类型unwrappd2=Unwrap//应为:string
.
.
.

如何定义展开?

可以使用映射和条件类型以及映射类型展开类型:

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

类型展开对象={
[P in keyof T]:展开
}
类型展开=T扩展类型?
U扩展对象?展开对象:U:
T扩展对象?展开对象:T
//其用法如下:
类型unwrappd1=Unwrap//应为:{a:boolean,b:{c:number}
类型unwrappd2=Unwrap//应为:string
声明出租人d:未包装1;
d、 b.c//编号