Demystifying Union and Intersection Types in TypeScript
Welcome to another TypeScript tutorial!
What are Union Types?
Union types allow you to combine multiple types into one.
let age: number | string;
age = 25; // Valid
age = 'twenty-five'; // Valid
In the above example, the variable age
can hold either a number
or a string
.
Use Cases of Union Types
Union types are useful in scenarios where a value can have different types or when we want to accept multiple types as function parameters.
Example 1: Creating a Function with Union Types
function displayData(data: number | string) {
console.log(data);
}
displayData(10); // Valid
displayData('Hello'); // Valid
In the above example, the displayData
function can accept both number
and string
types as parameters.
Example 2: Using Union Types for Variables
let result: number | boolean;
result = 10; // Valid
result = true; // Valid
The result
variable can store either a number
or a boolean
value.
What are Intersection Types?
Intersection types allow you to combine multiple types into one, creating a new type that has all the features of the intersected types.
interface A {
name: string;
}
interface B {
age: number;
}
let person: A & B = {
name: 'John',
age: 25
};
In the above example, the person
variable has both the name
property from interface A
and the age
property from interface B
.
Use Cases of Intersection Types
Intersection types are handy when you want to combine multiple types to create a new type.
Example 1: Combining Interfaces
interface Employee {
name: string;
age: number;
}
interface Manager {
teamSize: number;
}
type ManagerEmployee = Employee & Manager;
let manager: ManagerEmployee = {
name: 'John',
age: 30,
teamSize: 5
};
In the above example, the ManagerEmployee
type is created by combining the Employee
and Manager
interfaces.
Example 2: Combining Function Types
interface AddFunction {
(a: number, b: number): number;
}
interface SubtractFunction {
(a: number, b: number): number;
}
type MathOperations = AddFunction & SubtractFunction;
let math: MathOperations = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
In the above example, the MathOperations
type is created by intersecting the AddFunction
and SubtractFunction
interfaces.
Conclusion
Union and intersection types in TypeScript are powerful features that can enhance the flexibility and reusability of your code. By understanding their syntax and use cases, you can improve your TypeScript skills and write more robust and maintainable code.
Happy coding!