patterntypescriptCritical
typescript interface require one of two properties to exist
Viewed 0 times
typescriptexistpropertiesinterfacerequireonetwo
Problem
I'm trying to create an interface that could have
export interface MenuItem {
title: string;
component?: any;
click?: any;
icon: string;
}- Is there a way to require
componentorclickto be set
- Is there a way to require that both properties can't be set?
Solution
Not with a single interface, since types have no conditional logic and can't depend on each other, but you can by splitting the interfaces:
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;Code Snippets
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;Context
Stack Overflow Q#40510611, score: 223
Revisions (0)
No revisions yet.