Skip to content

Normalize union/intersection type combinations - #11717

Merged
Anders Hejlsberg (ahejlsberg) merged 4 commits into
masterfrom
normalizeIntersectionTypes
Oct 19, 2016
Merged

Normalize union/intersection type combinations#11717
Anders Hejlsberg (ahejlsberg) merged 4 commits into
masterfrom
normalizeIntersectionTypes

Conversation

@ahejlsberg

@ahejlsberg Anders Hejlsberg (ahejlsberg) commented Oct 18, 2016

Copy link
Copy Markdown
Member

With this PR we normalize combinations of intersection and union types based on the distributive property of the & type operator over the | type operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection types with union type constituents into equivalent union types with intersection type constituents and thus ensure that union types are always at the top level in type representations and equivalent ways of writing the same type are treated identically.

interface A { a: string }
interface B { b: string }
interface C { c: string }
interface D { d: string }

// Identical ways of writing the same type
type X1 = (A | B) & (C | D);
type X2 = A & (C | D) | B & (C | D);
type X3 = A & C | A & D | B & C | B & D;

In the example above, X1, X2, and X3 are all identical types that reference the normalized form A & C | A & D | B & C | B & D.

Fixes #9919.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One question about isRelatedTo and a possible improvement for reporting errors with intersections of boolean.

tests/cases/compiler/errorMessagesIntersectionTypes04.ts(18,5): error TS2322: Type 'A & B' is not assignable to type 'boolean'.
tests/cases/compiler/errorMessagesIntersectionTypes04.ts(19,5): error TS2322: Type 'A & B' is not assignable to type 'string'.
tests/cases/compiler/errorMessagesIntersectionTypes04.ts(21,5): error TS2322: Type 'number & boolean' is not assignable to type 'string'.
tests/cases/compiler/errorMessagesIntersectionTypes04.ts(21,5): error TS2322: Type '(number & true) | (number & false)' is not assignable to type 'string'.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there some way to present this error as number & boolean still? I feel like the distributed form is unexpected here.