Home > Enterprise >  Generate a type with the keys and values of an interface as value
Generate a type with the keys and values of an interface as value

Time:10-11

I have an interface which contains a key and a value and I want to create from that a type with the key as "type" and the value as "data".

I have this interface

interface NotificationInterface {
    "friends.invite": { userId: number }
    "notification": { url: string }
}

And I want to generate this

type NotificationData =
    | {
          type: "friends.invite"
          data: { userId: number }
      }
    | {
          type: "notification"
          data: { url: string }
      }

It is possible to create it automatically ?

CodePudding user response:

You can used a mapped type to transform each member of the interface to the desired shape, then use an indexed type to get the union:

interface NotificationInterface {
    "friends.invite": { userId: number }
    "notification": { url: string }
}
//  And I want to generate this

type Data<T> = {
    [P in keyof T]: {
        type: P
        data: T[P]
    }
}[keyof T]

type NotificationData = Data<NotificationInterface>

Playground Link

  • Related