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
?
答案 0 :(得分:2)
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>