Why can intersection types contain conflicting types?

Given two interfaces with conflicting member types:

interface A { x: number }
interface B { x: string }

It is not possible to define an interface that extends both:

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.

You can determine the type of intersection, which includes Aand B:

let c = A & B
type C = A & B 
// no type errors

Although it is not possible to instantiate this type:

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

Is there a technical reason why intersection types do not report conflicts when they are defined?

+4
source share
1 answer

typeoperands may be type parameters ; The operands interface... extendsmust be specific.

This difference makes it typemore flexible than interface(this is pretty much the motivation for type).

, type , , , .

Anders Hejlsberg,

() . , , (.. ). & . , , . , , , extends, ( ) &.

. Github .

+3

Source: https://habr.com/ru/post/1672052/


All Articles