打字稿界面 - 可以制作“一个或另一个"属性要求? [英] Typescript Interface - Possible to make "one or the other" properties required?

查看:23
本文介绍了打字稿界面 - 可以制作“一个或另一个"属性要求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是一个奇怪的问题,但我很好奇是否有可能制作一个需要一个属性或另一个属性的界面.

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

例如……

interface Message {
    text: string;
    attachment: Attachment;
    timestamp?: number;
    // ...etc
}

interface Attachment {...}

在上述情况下,我想确保 textattachment 存在.

In the above case, I'd like to make sure that either text or attachment exists.

希望这是有道理的.

提前致谢!

这就是我现在的做法.认为它有点冗长(为 slack 键入 botkit).

This is how I'm doing it right now. Thought it was a bit verbose (typing botkit for slack).

interface Message {
    type?: string;
    channel?: string;
    user?: string;
    text?: string;
    attachments?: Slack.Attachment[];
    ts?: string;
    team?: string;
    event?: string;
    match?: [string, {index: number}, {input: string}];
}

interface AttachmentMessageNoContext extends Message {
    channel: string;
    attachments: Slack.Attachment[];
}

interface TextMessageNoContext extends Message {
    channel: string;
    text: string;
}

推荐答案

您可以使用联合类型来做到这一点:

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);

这篇关于打字稿界面 - 可以制作“一个或另一个"属性要求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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