Intersection types let you combine multiple types into one. This helps you create a new type that has all the features of the combined types.
0
0
How intersection combines types in Typescript
Introduction
When you want an object to have properties from two or more types at the same time.
When you want to make sure a value meets multiple type requirements.
When combining different interfaces to create a more specific type.
When you want to add extra properties to an existing type without changing it.
Syntax
Typescript
type NewType = TypeA & TypeB;
The & symbol means intersection.
The new type has all properties from both TypeA and TypeB.
Examples
This creates
Employee with both name and job properties.Typescript
type Person = { name: string };
type Worker = { job: string };
type Employee = Person & Worker;Type
C has both a and b properties.Typescript
type A = { a: number };
type B = { b: string };
type C = A & B;Type
Z combines three types, so it has x, y, and z.Typescript
type X = { x: boolean };
type Y = { y: boolean };
type Z = X & Y & { z: number };Sample Program
This program creates an Employee type by combining Person and Contact. Then it makes an object with both name and email. Finally, it prints both values.
Typescript
type Person = { name: string };
type Contact = { email: string };
type Employee = Person & Contact;
const employee: Employee = {
name: "Alice",
email: "alice@example.com"
};
console.log(`Name: ${employee.name}`);
console.log(`Email: ${employee.email}`);OutputSuccess
Important Notes
If two types have the same property with different types, the intersection will require the property to satisfy both types, which can cause errors.
Intersection types are different from union types (|), which mean either one type or another.
Summary
Intersection types combine multiple types into one that has all their properties.
Use & to create intersection types.
They help make sure values meet all combined type requirements.