In TypeScript, intersection types allow you to combine multiple types into one. This is particularly useful when you want to create a type that has all the properties of the combined types. By using intersection types, you can enforce stricter contracts and avoid code duplication.
Intersection types are denoted by the & operator. When you intersect two or more types, the resulting type will have all the properties from each of those types.
The concept of intersection types is straightforward: it merges multiple types into a single type that includes all the properties of the individual types. This can be particularly useful when dealing with complex objects that need to conform to multiple interfaces or types.
For example, consider two interfaces:
interface Animal {
name: string;
}
interface Dog {
breed: string;
}
If you want a type that represents both an `Animal` and a `Dog`, you can use intersection types:
```typescript
type AnimalDog = Animal & Dog;
const myPet: AnimalDog = {
name: "Buddy",
breed: "Golden Retriever"
};
In this example, the `AnimalDog` type combines the properties of both `Animal` and `Dog`, resulting in a type that requires both `name` and `breed`.
## Examples
### Basic Intersection Types
Let's start with some basic examples to understand how intersection types work.
#### Example 1: Combining Interfaces
```typescript
interface Shape {
area(): number;
}
interface Colored {
color: string;
}
type ShapeWithColor = Shape & Colored;
const circle: ShapeWithColor = {
area: () => Math.PI * 5 * 5,
color: "red"
};
console.log(circle.area()); // Output: 78.53981633974483
console.log(circle.color); // Output: red
In this example, ShapeWithColor is an intersection of the Shape and Colored interfaces. The resulting type requires both an area method and a color property.
Intersection types can also be used to combine types with primitive types:
type NumberOrString = number | string;
type Positive = { positive: true };
type PositiveNumberOrString = NumberOrString & Positive;
const value1: PositiveNumberOrString = {
positive: true,
// This will cause a type error if uncommented:
// value: -5
};
const value2: PositiveNumberOrString = {
positive: true,
value: "Positive String"
};
In this example, `PositiveNumberOrString` is an intersection of the `NumberOrString` union and the `Positive` type. The resulting type requires both a `positive` property set to `true` and either a `number` or a `string`.
### Advanced Intersection Types
Intersection types can also be used in more complex scenarios, such as combining multiple interfaces with overlapping properties.
#### Example 3: Overlapping Properties
```typescript
interface Bird {
fly(): void;
}
interface Fish {
swim(): void;
}
type FlyingFish = Bird & Fish;
const goldenDorado: FlyingFish = {
fly: () => console.log("Flying"),
swim: () => console.log("Swimming")
};
goldenDorado.fly(); // Output: Flying
goldenDorado.swim(); // Output: Swimming
In this example, FlyingFish is an intersection of the Bird and Fish interfaces. The resulting type requires both a fly method and a swim method.
Intersection types can also be combined with utility types like Partial, Required, etc., to create more flexible types:
type OptionalShape = Partial<Shape>;
type RequiredColored = Required<Colored>;
type OptionalShapeWithRequiredColor = OptionalShape & RequiredColored;
const optionalCircle: OptionalShapeWithRequiredColor = {
color: "blue"
};
console.log(optionalCircle.color); // Output: blue
In this example, OptionalShapeWithRequiredColor is an intersection of the Partial<Shape> and Required<Colored> types. The resulting type requires a color property but allows other properties to be optional.
Now that you have a good understanding of intersection types, let's explore another advanced TypeScript feature: Literal Types. Literal types allow you to specify exact values for your variables, providing even more precise control over your code.
Stay tuned for the next section where we dive deeper into literal types and how they can be used in conjunction with other TypeScript features to create robust type systems!