Teresa
Teresa

Reputation: 349

Extend and add a new property to the existing type in Typescript

I am trying to extend and add a new property to the existing type in Typescript. Here's the illustration:

const menu = [
  {
    title: 'home'
  },
  'devider',
  {
    title: 'tools'
  },
  'devider',
  {
    body: 'addons'
  }
]

type Menu = typeof menu

Here's the type I got when using that code

type Menu = (string | {
    title: string;
    body?: undefined;
} | {
    body: string;
    title?: undefined;
})[]

Is it possible to extend 'Menu' type and add a new property (specifically not the string type) to become like this?

type Menu = (string | {
    title: string;
    active: boolean;
    body?: undefined;
} | {
    body: string;
    active: boolean;
    title?: undefined;
})[]

Thank you, really appreciate your help!

Upvotes: 0

Views: 1133

Answers (1)

A_blop
A_blop

Reputation: 862

You can remap the Menu type by making use of the infer keyword:

type Menu = (string | {
    title: string;
    body?: undefined;
} | {
    body: string;
    title?: undefined;
})[]

type MenuExtended = Menu extends (infer I)[] ?
    (I extends object ? I & { active: boolean } : I)[] :
    never

// better type display, otherwise same as MenuExtended
type MenuExtended2 = Menu extends (infer I)[] ?
    ((I extends object ? I & { active: boolean } : I) extends
        infer I2 ? { [K in keyof I2]: I2[K] } : never)[] :
    never

/*
type MenuExtended2 = (string | {
    title: string;
    body?: undefined;
    active: boolean;
} | {
    body: string;
    title?: undefined;
    active: boolean;
})[]

*/

Upvotes: 1

Related Questions