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

喜夏-厌秋 提交于 2019-12-04 02:28:59

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

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

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.

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"
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!