这个问题已经有了答案:
Unexpected behaviour using Index type with Union type signature
1个答案
打字本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.
TypeScript Playground
我原以为
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>