Understanding Typescript Intersection Types

Ole Ersoy
Oct 20, 2020
Image by chiplanay from Pixabay

Scenario

We have two interfaces. Interface A:

interface A { a: string }

And interface B:

interface B { b: number }

And we have a variable that has to contain the intersection of both interface types and we want to declare this.

Approach

var ab: A & B = { a: 'Hola!', b: 1 };

Note that because ab is of type A & B this will give a design time error:

var a: A & B = { a: "hola!" };

We are missing b .

Demo

Brought to You By

--

--