patterntypescriptCriticalCanonical
Typescript Interface - Possible to make "one or the other" properties required?
Viewed 0 times
typescriptpossibleotherpropertiestheinterfacerequiredonemake
Problem
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...
In the above case, I'd like to make sure that either
This is how I'm doing it right now. Thought it was a bit verbose (typing botkit for slack).
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:
If you want to allow both text and attachment, you would write
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);Code Snippets
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);Context
Stack Overflow Q#37688318, score: 159
Revisions (0)
No revisions yet.