Home > Net >  Create a type of nested inner object keys in typescript
Create a type of nested inner object keys in typescript

Time:07-13

I wanted to extract the inner elements and create a new type. For ex. to create an inner key type of:

    interface temp{
    a: {
        "aa":number
    }
    b:{
        "bb":number
    }
}

To create inner type dynamically I used:

type innerTemp={
    [k in keyof temp[keyof temp]]:temp[keyof temp][k]
}

I also tried this way:

 type innerTemp={
         [i in keyof T[k][k in keyof T]] : T[k][i]
    }

but it doesn't work the way I want. I want the inner interface to be like

 interface innerTemp{
     aa:number,
     bb:number,
 }

Can anyone please suggest a way to dynamically create inner type?

CodePudding user response:

This can be achieved with the UnionToIntersection type:

type UnionToIntersection<U> = 
  (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never

type InnerTemp = {
    [K in keyof UnionToIntersection<Temp[keyof Temp]>]: 
      UnionToIntersection<Temp[keyof Temp]>[K]
}

Playground

  • Related