HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
otherinterfaceonepropertiestherequiredtypescriptpossiblemake

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...

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

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.