简体   繁体   English

如果存在其他类型,如何使类型可选?

[英]How to make a type optional if other exists?

I want to create and interface for a component props.我想为组件道具创建和接口。 Currently it looks like this:目前它看起来像这样:

interface IContextMenuProps {
  text: string;
  image: string;
}

I want the text to be optional if image is provided and viceversa.如果提供图像,我希望文本是可选的,反之亦然。 On other words, one of them has to exist.换句话说,其中之一必须存在。

In your case you need to use union.在您的情况下,您需要使用联合。

Type will be something like this:类型将是这样的:

type IContextMenuProps = ({ text: string } | { image: string });

you can optional text key, something like.你可以选择文本键,比如。

type IContextMenuProps = ({ text: string } | { image: string });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM