0
0
Typescriptprogramming~5 mins

Intersection type syntax in Typescript

Choose your learning style9 modes available
Introduction

Intersection types let you combine multiple types into one. This means a value must have all the properties from each type.

When you want an object to have properties from two different types at the same time.
When combining features from multiple interfaces into one variable.
When you want to be sure a value meets several type requirements together.
Syntax
Typescript
type Combined = TypeA & TypeB;

The & symbol means 'and' in types.

The new type has all properties from both types.

Examples
This creates Employee type that has both name and job properties.
Typescript
type Person = { name: string };
type Worker = { job: string };
type Employee = Person & Worker;
Variable example must have both a and b properties.
Typescript
type A = { a: number };
type B = { b: number };
type C = A & B;

const example: C = { a: 1, b: 2 };
Sample Program

This program defines a type FlyingAnimal that combines Animal and Bird. The object parrot must have both name and canFly. It then prints these values.

Typescript
type Animal = { name: string };
type Bird = { canFly: boolean };
type FlyingAnimal = Animal & Bird;

const parrot: FlyingAnimal = {
  name: "Polly",
  canFly: true
};

console.log(`Name: ${parrot.name}`);
console.log(`Can fly: ${parrot.canFly}`);
OutputSuccess
Important Notes

If two types have the same property name but different types, intersection will require the property to satisfy both types, which can cause errors.

Intersection types are useful to build complex types from simple ones.

Summary

Intersection types combine multiple types into one.

Use & to join types.

The resulting type has all properties from each combined type.