Union & Intersection Types in TypeScript (Live Playground)
In this tutorial, we will explore union and intersection types in TypeScript. Understanding how to use union and intersection types will enable you to create flexible and type-safe code.
Union Types
Union types allow you to create a type that can be one of several types. You can define a union type using the |
(pipe) operator between the types:
type StringOrNumber = string | number;
function printValue(value: StringOrNumber): void {
console.log(value);
}
printValue('Hello'); // Output: Hello
printValue(42); // Output: 42
In this example, we create a union type StringOrNumber
that can be either a string
or a number
. We then use the StringOrNumber
type in the printValue
function.
Intersection Types
Intersection types allow you to create a type that combines multiple types into one. You can define an intersection type using the &
(ampersand) operator between the types:
interface Person {
name: string;
age: number;
}
interface Employee {
title: string;
salary: number;
}
type FullTimeEmployee = Person & Employee;
const employee: FullTimeEmployee = {
name: 'John Doe',
age: 30,
title: 'Software Developer',
salary: 80000,
};
In this example, we create two interfaces Person
and Employee
and then create an intersection type FullTimeEmployee
that combines the properties of both interfaces.
Using Union and Intersection Types
Union and intersection types can be used in a variety of scenarios to create more flexible and type-safe code:
- Combining multiple types into one, for example, by creating a type that represents both a user and an administrator.
- Defining function parameters that can accept multiple types, for example, a function that can accept either a string or an array of strings.
- Creating reusable and type-safe utility functions that can work with different types, for example, a generic
merge
function that can merge objects of different types.
Conclusion
In this tutorial, we have explored union and intersection types in TypeScript. Understanding how to use union and intersection types effectively will enable you to create flexible and type-safe code.
In the upcoming tutorials, we will continue to explore advanced TypeScript concepts, such as generics, conditional types, mapped types, and more. As you progress through these tutorials, you will gain a deeper understanding of TypeScript's features and how to use them effectively in your projects.