3.8 Intersection types

Anders Hejlsberg, the creator of TypeScript, describes intersection types as:

Intersection types are the logical complement of union types. A union type A | B represents an entity that has either type A or type B, whereas an intersection type A & B represents an entity that has both type A and type B.

Getting Ready

All you need to be able to use intersection types is an installation of TypeScript 2.0 or higher.

How to do it…

Let’s start by declaring a few types:

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

Now, we can use the intersection type operator (&) to create a new intersection type:

let abc: A & B & C;

How it works…

The intersection type abc includes all the method and properties declared by the A, B and C interfaces:

abc.a = 'hello';
abc.b = 'hello';
abc.c = 'hello';

There’s more…

When a member is available in two or more of the types used to create an intersection type under the same name but different type:

interface X { x: A }
interface Y { x: B }
interface Z { x: C }
let xyz: X & Y & Z;

The member in the resulting intersection type will be available under the same name but will contain all the properties from the types involved in the intersection:

xyz.x.a = 'hello';
xyz.x.b = 'hello';
xyz.x.c = 'hello';

This behavior is similar to the usage of the following mixins:

  applyMixins(xyz.x, [xyz.x, xyz.x]);

Source Code

Intersection types

See also

Please refer to the recipes about <div class="important-text">union types</div> & <div class="important-text">mixins</div> in this chapter to learn more about them.

Shiv Kushwaha