Typescript Interface - Possible to make “one or the other” properties required?

前端 未结 6 1788
梦谈多话
梦谈多话 2020-12-02 18:06

Possibly an odd question, but i\'m curious if it\'s possible to make an interface where one property or the other is required.

So, for example...

int         


        
6条回答
  •  时光说笑
    2020-12-02 18:37

    You can use a union type to do this:

    interface MessageBasics {
      timestamp?: number;
      /* more general properties here */
    }
    interface MessageWithText extends MessageBasics {
      text: string;
    }
    interface MessageWithAttachment extends MessageBasics {
      attachment: Attachment;
    }
    type Message = MessageWithText | MessageWithAttachment;
    

    If you want to allow both text and attachment, you would write

    type Message = MessageWithText | MessageWithAttachment | (MessageWithText & MessageWithAttachment);
    

提交回复
热议问题