【发布时间】:2017-11-09 13:21:02
【问题描述】:
我如何说我想要一个界面是一个或另一个,但不是两者兼而有之?
interface IFoo {
bar: string /*^XOR^*/ can: number;
}
【问题讨论】:
标签: typescript interface schema xor typescript2.0
我如何说我想要一个界面是一个或另一个,但不是两者兼而有之?
interface IFoo {
bar: string /*^XOR^*/ can: number;
}
【问题讨论】:
标签: typescript interface schema xor typescript2.0
您可以使用联合类型和 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
【讨论】:
never 可以用来禁止密钥出现!
+1 & 接受
let val2: IFoo = { bar: "hello", can: undefined }
如this issue 中所建议,您可以使用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
【讨论】:
XOR<A | B | C | D> 怎么样?
您可以通过 union 和可选的void type 获得“一个而不是另一个”:
type IFoo = {bar: string; can?: void} | {bar?:void; can: number};
但是,您必须使用 --strictNullChecks 来防止两者都没有。
【讨论】:
试试这个:
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"
}
【讨论】: