带有 XOR 的 TypeScript 接口,{bar:string} xor {can:number}

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

我想要一个接口是其中之一,而不是两者兼而有之,怎么说?

interface IFoo {
    bar: string /*^XOR^*/ can: number;
}

试试这个:

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

你可以得到 "one but not the other" 联合和可选 void type:

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

但是,您必须使用 --strictNullChecks 来防止两者都没有。

您可以将联合类型与 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

建议在this issue, you can use conditional types (introduced in Typescript 2.8)写一个异或类型:

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;

你可以这样使用它:

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