Appearance
Intersection Types
Intersection types combine multiple types using the & operator. They represent types that have all the properties and methods from each of the combined types.
What are they?
An intersection type A & B represents a type that has all the properties and methods from both type A and type B. Think of it as "AND" logic - the resulting type must satisfy both types simultaneously.
Combining Types
ts
type Shape = { colour: string };
type Square = Shape & { size: number };
type ColouredSquare = Square & { border: string };
// Usage:
let square: Square = { colour: "red", size: 10 };
let fancySquare: ColouredSquare = { colour: "blue", size: 15, border: "dashed" };Many Types
You can combine more than two types:
ts
type HasName = { name: string };
type HasAge = { age: number };
type HasEmail = { email: string };
type Person = HasName & HasAge & HasEmail;
// Person must have all three properties:
const person: Person = {
name: "Alice",
age: 30,
email: "alice@example.com"
};With Function Types
Intersection types can combine function signatures:
ts
type StringProcessor = (text: string) => string;
type NumberProcessor = (num: number) => number;
type UniversalProcessor = StringProcessor & NumberProcessor;
// This creates a function that can handle both string and number inputs
const processor: UniversalProcessor = (input: string | number) => {
if (typeof input === "string") {
return input.toUpperCase();
} else {
return input * 2;
}
};
console.log(processor("hello")); // "HELLO"
console.log(processor(5)); // 10With Union Types
You can combine intersection and union types:
ts
type StringOrNumber = string | number;
type HasLength = { length: number };
type StringOrNumberWithLength = StringOrNumber & HasLength;
// This creates a type that can be either a string or number, but must have a length property
const value1: StringOrNumberWithLength = "hello"; // string has length
const value2: StringOrNumberWithLength = [1, 2, 3]; // array has length
// const value3: StringOrNumberWithLength = 42; // Error: number doesn't have lengthvs. Union Types
It's important to understand the difference:
ts
// Union type: can be EITHER type A OR type B
type StringOrNumber = string | number;
// Intersection type: must be BOTH type A AND type B
type StringAndNumber = string & number; // This is actually never (impossible)
// More realistic example:
type HasName = { name: string };
type HasAge = { age: number };
// Union: can have name OR age (or both)
type NameOrAge = HasName | HasAge;
// Intersection: must have BOTH name AND age
type NameAndAge = HasName & HasAge;External Resources