Categories
TypeScript Answers

How to require one of two properties to exist in a TypeScript interface?

Spread the love

To require one of two properties to exist in a TypeScript interface, we can combine multiple interfaces with the | operator, which create a union type.

For instance, we write

export interface BaseMenuItem {
  title: string;
  icon: string;
}

export interface ComponentMenuItem extends BaseMenuItem {
  component: any;
}

export interface ClickMenuItem extends BaseMenuItem {
  click: any;
}

export type MenuItem = ComponentMenuItem | ClickMenuItem;

to create a union type between ComponentMenuItem and ClickMenuItem and assign it to the MenuItem type.

In ComponentMenuItem and ClickMenuItem, there’s one extra property and inherits the rest from BaseMenuItem.

Therefore a variable with type MenuItem has either the component or click property in addition to the properties in BaseMenuItem.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *