In this tutorial, we will explore the concept of intersection and union types in TypeScript. These are powerful features that allow us to create complex types, which can hold different kinds of values.
By the end of this tutorial, you will understand what intersection and union types are, how to use them, and where they can be beneficial in your TypeScript code.
You should have a basic understanding of TypeScript and its type system. Familiarity with JavaScript will also be helpful.
Intersection types are a way of combining multiple types into one. This allows you to add together existing types to get a single type that has all the features you need.
Here's a basic example:
type First = { a: number; b: number; };
type Second = { b: string; c: string; };
type Combined = First & Second;
In this case, Combined
is a type which has all the properties of First
and Second
types.
Union types are about adding more types to a particular variable, allowing it to hold different types of values. Unlike intersection types, a variable with a union type can hold any one type of value from those specified in the union.
Here's a basic example:
type StringOrNumber = string | number;
In this case, a variable of type StringOrNumber
can hold either a string
or a number
.
type Employee = { name: string; };
type Manager = { employees: Employee[]; };
type CEO = Employee & Manager;
let ceo: CEO = {
name: 'John',
employees: [{ name: 'Jane' }, { name: 'Joe' }]
};
In this example, the CEO
type is an intersection of Employee
and Manager
. Therefore, a CEO
has both a name
and employees
.
type StringOrNumber = string | number;
let input: StringOrNumber;
input = 'Hello'; // valid
input = 42; // valid
input = true; // Error: Type 'boolean' is not assignable to type 'StringOrNumber'
In this example, the input
variable can be either a string
or a number
. Any other type would cause an error.
In this tutorial, we've learned about intersection and union types in TypeScript. Intersection types allow us to create a new type with properties from multiple other types, while union types allow a variable to hold a value of different types.
To continue learning, you might want to explore other advanced types in TypeScript like type guards, type aliases, and discriminated unions.
Create an intersection type that combines two object types with different properties. Use this type to create an object that has properties from both types.
Create a union type that can hold either a string, number, or boolean. Use this type to create a variable that can hold values of these types.
Create a function that accepts a parameter of a union type you created. Inside the function, use type guards to determine the type of the parameter and perform different actions based on that.
Remember to practice and apply these concepts in real TypeScript projects to solidify your understanding. Happy coding!