Intersection Types
Intersection Types Express "and"#
Intersection types allow us to express "AND" relationship between types. They are relevant for object types, but not for primitives as a value cannot be multiple primitives at the same time.
Intersections can be used to extend object types, allowing us to create new types that build off of existing ones. In the example below, we use the intersection operator, &
, to create the FoodProduct
type as an intersection of Product
and Food
:
1
type Product = {
2
title: string;
3
price: number;
4
};
5
6
type Food = {
7
calories: number;
8
ingredients: string[]
9
}
10
11
type FoodProduct = Food & Product;
The order of the types in an intersection expression is irrelevant and the resulting type will be the same regardless. This means we could have written FoodProduct
like so:
1
type FoodProduct = Product & Food; // same as Food & Product
FoodProduct
is assignable to objects that have properties from both Food
and Product
:
1
const cereal: FoodProduct = {
2
title: 'Kellogs',
3
price: 5.99,
4
calories: 100,
5
ingredients: ['wheat', 'sugar'],
6
}; // OK
7
8
const steak: FoodProduct = {
9
title: 'T-bone',
10
ingredients: ['meat'],
11
calories: 300,
12
}; // Error: missing 'price'
This page is a preview of Beginners Guide to TypeScript