Search code examples
typescriptinterfaceschemaxortypescript2.0

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


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

Solution

  • 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