- TypeScript 3.2.2
- 有两种具有不同属性的类型:
A
和B
. - 我想接受
A
或B
,但想在 the intersection type 上抛出错误两者中的一个。
例如:
type A = { a: number }
type B = { b: number }
var a: A = { a: 1, b: 1 } //← Property 'b' is invalid. Fine.
var b: B = { a: 1, b: 1 } //← Property 'a' is invalid. Fine.
var c: A | B = { a: 1, b: 1 } //← I expected to be an error because this value is
// compatible with neither A nor B, but allowed.
var d: A & B = { a: 1, b: 1 } //← OK because this is the intersection type.
我期望 A | B
成为我想要的人,但事实并非如此。
我怎样才能接受A
或B
,但不是A & B
?
最佳答案
TypeScript 中的联合是包容性的,而不是排他性的。您可以像这样建立排它联合:
type ProhibitKeys<K extends keyof any> = { [P in K]?: never }
type Xor<T, U> = (T & ProhibitKeys<Exclude<keyof U, keyof T>>) |
(U & ProhibitKeys<Exclude<keyof T, keyof U>>);
type A = { a: number }
type B = { b: number }
var a: Xor<A, B> = { a: 1 }; // okay
var b: Xor<A, B> = { b: 1 }; // okay
var c: Xor<A, B> = { a: 1, b: 1 }; // error,
// {a: number, b: number} not assignable to Xor<A, B>
关于typescript - 如何抛出对象交集类型的语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54121258/