0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.