Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; } 
like image 290
A T Avatar asked Jun 08 '17 01:06

A T


1 Answers

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 
like image 107
Saravana Avatar answered Oct 02 '22 09:10

Saravana