Here’s a rewritten version of the article:

Unlocking the Power of TypeScript: Union and Intersection Types

When working with TypeScript, it’s essential to understand how to combine multiple data types to create more flexible and robust variables. This is where Union and Intersection types come into play. These powerful features allow you to define variables that can be one of many types or must satisfy all types, respectively.

The Versatility of Union Types

A Union type enables a variable to take on multiple specified types. Think of it as saying “a variable can be A or B.” For instance, let’s define a variable value that can hold either a string or a number:

let value: string | number;

Notice the use of the | symbol to define the Union type. This flexibility is particularly useful when working with function parameters. For example, consider a printId() function that accepts an id parameter that can be either a number or a string:

function printId(id: string | number) {... }

The Power of Intersection Types

An Intersection type, on the other hand, merges multiple types into one. A value of this type must include all properties from each of the combined types. You can define an Intersection type using the & symbol. For example:

type resultingType = typeA & typeB;

Here, resultingType must satisfy both typeA and typeB, meaning it must have all their required properties.

Building Complex Types with Intersections

You can create complex types by intersecting two or more types. For instance, let’s define a Person type that combines Name and Age:

type Person = Name & Age;

This means that any value of the Person type must include both the name and age properties. When we define person1 of the Person type, it must contain both fields.

let person1: Person = { name: 'John', age: 30 };

You can take it a step further by intersecting multiple types. For example:

type FullPerson = Name & Age & Address;

Now, person must include all three properties: name, age, and city.

By mastering Union and Intersection types, you’ll be able to create more expressive and flexible code that’s easier to maintain and scale.

Leave a Reply