23

How do I say that I want an interface to be one or the other, but not both or neither?

interface IFoo {
    bar: string /*^XOR^*/ can: number;
}
A T
  • 10,508
  • 14
  • 85
  • 137

4 Answers4

39

You can use union types along with the never type to achieve this:

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
Saravana
  • 28,153
  • 11
  • 81
  • 94
18

As proposed in this issue, you can use conditional types (introduced in Typescript 2.8) to write a XOR type:

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;

And you can use it like so:

type IFoo = XOR<{bar: string;}, {can: number}>;
let test: IFoo;
test = { bar: "test" } // OK
test = { can: 1 } // OK
test = { bar: "test",  can: 1 } // Error
test = {} // Error
  • Fancy.................................. – A T Nov 11 '18 at 08:18
  • 6
  • @trusktr I think it boilds down to [variadic generics](https://github.com/microsoft/TypeScript/issues/1773) in combination with TS3.1. Unfortunately I have not come up with a solution for this myself yet. But I can think of using Head, Tail, HasTail and recursion as demonstrated here: https://www.freecodecamp.org/news/typescript-curry-ramda-types-f747e99744ab/. On the downside of things, this does not check on the permutation set and I do not know if that does collide with operations in set theory (such as triangle inequality). – tahesse May 10 '20 at 09:12
4

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

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

However, you have to use --strictNullChecks to prevent having neither.

artem
  • 29,391
  • 6
  • 61
  • 63
1

try this:

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"
}
Hoang Hiep
  • 1,390
  • 4
  • 11
  • 17