TypeScript interface with XOR, {bar: string} xor {can: number}

How can I say that I want the interface to be one way or another, but not both, or in any way?

interface IFoo {
    bar: string /*^XOR^*/ can: number;
}
+4
source share
3 answers

To achieve this, you can use union types together with never:

type IFoo = {
  bar: string; can?: never
} | {
    bar?: never; can: number
  };


let val0: IFoo = { bar: "hello" } // OK only bar
let val1: IFoo = { can: 22 } // OK only can
let val2: IFoo = { bar: "hello",  can: 22 } // Error foo and can
let val3: IFoo = {  } // Error neither foo or can
+9
source

You can get one and not the other with a union and optional void type :

type IFoo = {bar: string; can?: void} | {bar?:void; can: number};

However, you need to use it --strictNullChecksin order to have neither one nor the other.

+3
source

:

type Foo = {
    bar?: void;
    foo: string;
}

type Bar = {
    foo?: void;
    bar: number;
}

type FooBar = Foo | Bar;

// Error: Type 'string' is not assignable to type 'void'
let foobar: FooBar = {
    foo: "1",
    bar: 1
}

// no errors
let foo = {
    foo: "1"
}
+1

Source: https://habr.com/ru/post/1678749/


All Articles