打字稿接口需要存在两个属性之一 [英] typescript interface require one of two properties to exist

查看:24
本文介绍了打字稿接口需要存在两个属性之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个可以具有

I'm trying to create an interface that could have

export interface MenuItem {
  title: string;
  component?: any;
  click?: any;
  icon: string;
}

  1. 有没有办法要求设置componentclick
  2. 有没有办法要求不能设置这两个属性?

推荐答案

不是单一的接口,因为类型没有条件逻辑并且不能相互依赖,但是你可以通过拆分接口:

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;

这篇关于打字稿接口需要存在两个属性之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆