可能是一个奇怪的问题,但我很好奇是否可以制作一个需要一个属性或另一个属性的接口。
所以,例如…
interface Message { text: string; attachment: Attachment; timestamp?: number; // ...etc } interface Attachment {...}
在上述情况下,我想确保要么存在text要么attachment存在。
text
attachment
这就是我现在正在做的事情。认为它有点冗长(为 slack 键入 botkit)。
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; }
您可以使用联合类型来执行此操作:
interface MessageBasics { timestamp?: number; /* more general properties here */ } interface MessageWithText extends MessageBasics { text: string; } interface MessageWithAttachment extends MessageBasics { attachment: Attachment; } type Message = MessageWithText | MessageWithAttachment;
如果你想同时允许文本和附件,你会写
type Message = MessageWithText | MessageWithAttachment | (MessageWithText & MessageWithAttachment);