给定两个接口与冲突的成员类型:交集类型为什么可能包含冲突类型?
interface A { x: number }
interface B { x: string }
这是不可能的,以限定延伸两者的接口:
interface I extends A, B
// error TS2320: Interface 'I' cannot simultaneously extend types 'A' and 'B'.
// Named property 'x' of types 'A' and 'B' are not identical.
它是可能定义包括A
和交叉路口型B
:
let c = A & B
type C = A & B
// no type errors
尽管它是不可能创建此类型的实例:
let withNumber: C = { x: 10 }
error TS2322: Type '{ x: number; }' is not assignable to type 'A & B'.
Type '{ x: number; }' is not assignable to type 'B'.
Types of property 'x' are incompatible.
Type 'number' is not assignable to type 'string'.
let withString: C = { x: "foo" }
// The same type error, with `number` and `string` reversed
是否有技术原因,他们被定义在那个路口的类型不报告冲突?
可以定义该接口:'interface I extends A,B {x:number&string}'! –