Issue
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...
interface Message {
text: string;
attachment: Attachment;
timestamp?: number;
// ...etc
}
interface Attachment {...}
In the above case, I'd like to make sure that either text
or attachment
exists.
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;
}
Solution
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);
Answered By - Ryan Cavanaugh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.