DEV Community

Cover image for Typescript - Tips & Tricks - Union and Intersection
Luca Del Puppo for This is Learning

Posted on • Edited on

6 2

Typescript - Tips & Tricks - Union and Intersection

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'.
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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 };
Enter fullscreen mode Exit fullscreen mode

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!

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay