Typescript - Tips & Tricks - Union and Intersection

Hi and welcome back! Today I talk about Union and Intersection. In some cases, we have to combine...

#typescript #webdev
Luca Del Puppo Luca Del Puppo
Article Series · Part 4 of 21 TypeScript - Tips & Tricks
View full series (21)
  1. #3 Previous
    keyof
  2. #4 Reading now
    Union and Intersection
  3. #5 Up next
    Overloaded Functions
Browse all 21 parts in this series
  1. #1 typeof
  2. #2 Literal Types
  3. #3 keyof
  4. #4 Union and Intersection Current
  5. #5 Overloaded Functions
  6. #6 this parameter
  7. #7 any vs. unknown
  8. #8 Optional modifier
  9. #9 Index Signature
  10. #10 readonly modifier
  11. #11 Readonly Array
  12. #12 Tuple
  13. #13 Non-null assertion operator
  14. #14 Never type
  15. #15 Assert Function
  16. #16 Type Guard
  17. #17 Conditional Type
  18. #18 infer keyword
  19. #19 Mapped Types
  20. #20 Advanced Types
  21. #21 Rest Parameters & Rest Arguments

Hi and welcome back! Today I talk about Union and Intersection.

In some cases, we have to combine different types to create new types, or sometimes we have parameters that could be of different types. Typescript helps us with two powerful features: Union(|) and Intersection(&).

Union

A union type describes a value that can be one of several types.

type Padding = number | string
let paddingNumber: Padding = 1
let paddingString: Padding = '----';
let paddingError: Padding = true // Type 'boolean' is not assignable to type 'Padding'.

In this case, the padding can be a number or a string, and the compiler detects if you set different types; this feature can be used also with custom types.

type Fish = {
  name(): string;
  swim(): true;
};
type Cat = {
  name(): string;
  meows(): true;
};
type Pet = Fish | Cat; // { name(): string; }
declare function createPet(): Pet;
let pet = createPet();
pet.name()
pet.swim() // Property 'swim' does not exist on type 'Pet'
pet.meows(); // Property 'meows' does not exist on type 'Pet'

In this example we can see how the union type creates the Pet type; the Pet type is composed by a single method “name”. This method is the only one present in the two initial types: Fish and Cat.

Intersection

An intersection type combines multiple types into one.

type Point2D = {
  x: number;
  y: number;
};
type Point3D = Point2D & {
  z: number;
};
let point2d: Point2D = { x: 0, y: 0 };
let point3d: Point3D = { x: 0, y: 0, z: 0 };

We can see that the Point3D type is the union of the Type Point2D and the type { z: number; }.

That’s all for today! See you soon guys!

Luca Del Puppo

Written by Luca Del Puppo

Run, Code & Learn

AI Native Engineer at Nearform based in Povegliano (TV), Italy. Google Developer Expert in Web Technologies, GitKraken Ambassador, and Codemotion Ambassador.