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

Typescript

Typescript Problem Overview


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

Typescript Solutions


Solution 1 - Typescript

If you're truly after "one property or the other" and not both you can use never in the extending type:

interface MessageBasics {
  timestamp?: number;
  /* more general properties here */
}
interface MessageWithText extends MessageBasics {
  text: string;
  attachment?: never;
}
interface MessageWithAttachment extends MessageBasics {
  text?: never;
  attachment: string;
}
type Message = MessageWithText | MessageWithAttachment;

// 👍 OK 
let foo: Message = {attachment: 'a'}

// 👍 OK
let bar: Message = {text: 'b'}

// ❌ ERROR: Type '{ attachment: string; text: string; }' is not assignable to type 'Message'.
let baz: Message = {attachment: 'a', text: 'b'}

Example in Playground

Solution 2 - Typescript

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

Solution 3 - Typescript

You can go deeper with @robstarbuck solution creating the following types:

type Only<T, U> = {
  [P in keyof T]: T[P];
} & {
  [P in keyof U]?: never;
};

type Either<T, U> = Only<T, U> | Only<U, T>;

And then Message type would look like this

interface MessageBasics {
  timestamp?: number;
  /* more general properties here */
}
interface MessageWithText extends MessageBasics {
  text: string;
}
interface MessageWithAttachment extends MessageBasics {
  attachment: string;
}
type Message = Either<MessageWithText, MessageWithAttachment>;

With this solution you can easily add more fields in MessageWithText or MessageWithAttachment types without excluding it in another.

Solution 4 - Typescript

Thanks @ryan-cavanaugh that put me in the right direction.

I have a similar case, but then with array types. Struggled a bit with the syntax, so I put it here for later reference:

interface BaseRule {
  optionalProp?: number
}

interface RuleA extends BaseRule {
  requiredPropA: string
}

interface RuleB extends BaseRule {
  requiredPropB: string
}

type SpecialRules = Array<RuleA | RuleB>

// or

type SpecialRules = (RuleA | RuleB)[]

// or (in the strict linted project I'm in):

type SpecialRule = RuleA | RuleB
type SpecialRules = SpecialRule[]

Update:

Note that later on, you might still get warnings as you use the declared variable in your code. You can then use the (variable as type) syntax. Example:

const myRules: SpecialRules = [
  {
    optionalProp: 123,
    requiredPropA: 'This object is of type RuleA'
  },
  {
    requiredPropB: 'This object is of type RuleB'
  }
]

myRules.map((rule) => {
  if ((rule as RuleA).requiredPropA) {
    // do stuff
  } else {
    // do other stuff
  }
})

Solution 5 - Typescript

You can create few interfaces for the required conditions and join them in a type like here:

interface SolidPart {
    name: string;
    surname: string;
    action: 'add' | 'edit' | 'delete';
    id?: number;
}
interface WithId {
    action: 'edit' | 'delete';
    id: number;
}
interface WithoutId {
    action: 'add';
    id?: number;
}

export type Entity = SolidPart & (WithId | WithoutId);

const item: Entity = { // valid
    name: 'John',
    surname: 'Doe',
    action: 'add'
}
const item: Entity = { // not valid, id required for action === 'edit'
    name: 'John',
    surname: 'Doe',
    action: 'edit'
}

Solution 6 - Typescript

I've stumbled upon this thread when looking for an answer for my case (either propA, propB or none of them). Answer by Ryan Fujiwara almost made it but I've lost some checks by that.

My solution:

interface Base {   
  baseProp: string; 
}

interface ComponentWithPropA extends Base {
  propA: string;
  propB?: never;
}

interface ComponentWithPropB extends Base {
  propB: string;
  propA?: never;
} 

interface ComponentWithoutProps extends Base {
  propA?: never;
  propB?: never;
}

type ComponentProps = ComponentWithPropA | ComponentWithPropB | ComponentWithoutProps;

This solution keeps all checks as they should be. Perhaps someone will find this useful :)

Solution 7 - Typescript

You can also use an abstract class for the general properties instead of an interface, to prevent someone from accidentally implementing that interface.

abstract class BaseMessage {
  timestamp?: number;
  /* more general properties here */
  constructor(timestamp?: number) {
    this.timestamp = timestamp;
    /* etc. for other general properties */
  }
}
interface IMessageWithText extends BaseMessage {
  text: string;
  attachment?: never;
}
interface IMessageWithAttachment extends BaseMessage {
  text?: never;
  attachment: string;
}
type Message = IMessageWithText | IMessageWithAttachment;

Solution 8 - Typescript

There're some cool Typescript option that you could use https://www.typescriptlang.org/docs/handbook/utility-types.html#omittk

Your question is: make an interface where either 'text' or attachment exist. You could do something like:

interface AllMessageProperties {
  text: string,
  attachement: string,
}

type Message = Omit<AllMessageProperties, 'text'> | Omit<AllMessageProperties, 'attachement'>;

const messageWithText : Message = {
  text: 'some text'
}

const messageWithAttachement : Message = {
  attachement: 'path-to/attachment'
}

const messageWithTextAndAttachement : Message = {
  text: 'some text',
  attachement: 'path-to/attachment'
}

// results in Typescript error
const messageWithOutTextOrAttachement : Message = {

}

Solution 9 - Typescript

Ok, so after while of trial and error and googling I found that the answer didn't work as expected for my use case. So in case someone else is having this same problem I thought I'd share how I got it working. My interface was such:

export interface MainProps {
  prop1?: string;
  prop2?: string;
  prop3: string;
}

What I was looking for was a type definition that would say that we could have neither prop1 nor prop2 defined. We could have prop1 defined but not prop2. And finally have prop2 defined but not prop1. Here is what I found to be the solution.

interface MainBase {
  prop3: string;
}

interface MainWithProp1 {
  prop1: string;
}

interface MainWithProp2 {
  prop2: string;
}

export type MainProps = MainBase | (MainBase & MainWithProp1) | (MainBase & MainWithProp2);

This worked perfect, except one caveat was that when I tried to reference either prop1 or prop2 in another file I kept getting a property does not exist TS error. Here is how I was able to get around that:

import {MainProps} from 'location/MainProps';

const namedFunction = (props: MainProps) => {
    if('prop1' in props){
      doSomethingWith(props.prop1);
    } else if ('prop2' in props){
      doSomethingWith(props.prop2);
    } else {
      // neither prop1 nor prop2 are defined
    }
 }

Just thought I'd share that, cause if I was running into that little bit of weirdness then someone else probably was too.

Solution 10 - Typescript

Nobody has mentioned it so far, but I think that whoever stumbles upon this page may also consider using discriminated unions. If I properly understood the intensions of the OP's code then it might be transformed like this.

interface Attachment {}

interface MessageBase {
    type?: string;
    user?: string;
    ts?: string;
    team?: string;
    event?: string;
    match?: [string, {index: number}, {input: string}];
}

interface AttachmentMessageNoContext extends MessageBase {
    kind: 'withAttachments',
    channel: string;
    attachments: Attachment[];
}

interface TextMessageNoContext extends MessageBase {
    kind: 'justText', 
    channel: string;
    text: string;
}

type Message = TextMessageNoContext | AttachmentMessageNoContext

const textMessage: Message = {
  kind: 'justText',
  channel: 'foo',
  text: "whats up???" 
}

const messageWithAttachment: Message = {
  kind: 'withAttachments',
  channel: 'foo',
  attachments: []
}

Now Message interface requires either attachments or text depending on the kind property.

Solution 11 - Typescript

Simple 'need one of two' example:

type Props =
  | { factor: Factor; ratings?: never }
  | { ratings: Rating[]; factor?: never }

Solution 12 - Typescript

Without using extension

Using XOR described here: https://stackoverflow.com/a/53229567/8954109

// Create a type that requires properties `a` and `z`, and one of `b` or `c`
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;

interface Az {
  a: number;
  z: number;
}

interface B {
  b: number;
}

interface C {
  c: number;
}

type XorBC = XOR<B, C>;
type AndAzXorBC = Az & XorBC;
type MyData = AndAzXorBC;

const ok1: MyData = { a: 0, z: 1, b: 2 };
const ok2: MyData = { a: 0, z: 1, c: 2 };
const badBothBC: MyData = {
  a: 0, z: 1,
  b: 2,
  c: 3
};
const badNoBC: MyData = { a: 0, z: 1 };
const badNoZ: MyData = { a: 0, b: 2 };

Produces these errors for invalid types:

src/App.tsx:30:7 - error TS2322: Type '{ a: number; z: number; b: number; c: number; }' is not assignable to type 'AndAzXorBC'.
  Type '{ a: number; z: number; b: number; c: number; }' is not assignable to type 'Az & Without<C, B> & B'.
    Type '{ a: number; z: number; b: number; c: number; }' is not assignable to type 'Without<C, B>'.
      Types of property 'c' are incompatible.
        Type 'number' is not assignable to type 'undefined'.

30 const badBothBC: MyData = {
src/App.tsx:35:7 - error TS2322: Type '{ a: number; z: number; }' is not assignable to type 'AndAzXorBC'.
  Type '{ a: number; z: number; }' is not assignable to type 'Az & Without<C, B> & B'.
    Property 'b' is missing in type '{ a: number; z: number; }' but required in type 'B'.

35 const badNoBC: MyData = { a: 0, z: 1 };
         ~~~~~~~

  src/App.tsx:17:3
    17   b: number;
         ~
    'b' is declared here.
src/App.tsx:36:7 - error TS2322: Type '{ a: number; b: number; }' is not assignable to type 'AndAzXorBC'.
  Type '{ a: number; b: number; }' is not assignable to type 'Az & Without<C, B> & B'.
    Property 'z' is missing in type '{ a: number; b: number; }' but required in type 'Az'.

36 const badNoZ: MyData = { a: 0, b: 2 };
         ~~~~~~

  src/App.tsx:13:3
    13   z: number;
         ~
    'z' is declared here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondsiffordView Question on Stackoverflow
Solution 1 - TypescriptrobstarbuckView Answer on Stackoverflow
Solution 2 - TypescriptRyan CavanaughView Answer on Stackoverflow
Solution 3 - TypescriptVoskanyan DavidView Answer on Stackoverflow
Solution 4 - TypescriptpublicJornView Answer on Stackoverflow
Solution 5 - TypescriptcuddlemeisterView Answer on Stackoverflow
Solution 6 - TypescriptDarekView Answer on Stackoverflow
Solution 7 - TypescriptEdvin LarssonView Answer on Stackoverflow
Solution 8 - TypescriptStefan van de VoorenView Answer on Stackoverflow
Solution 9 - TypescriptRyanFujiView Answer on Stackoverflow
Solution 10 - TypescriptansavchencoView Answer on Stackoverflow
Solution 11 - TypescriptShahView Answer on Stackoverflow
Solution 12 - Typescriptplswork04View Answer on Stackoverflow