Intersection Types in TypeScript
Intersection types in TypeScript allow you to combine multiple types into a single type. This is useful when you need a variable or function parameter to satisfy multiple type constraints. Intersection types are created using the ampersand (&
) symbol between types.
Basic Usage
Intersection types combine the properties of multiple types into one. Here is an example of how to declare and use an intersection type:
interface Person {
name: string;
age: number;
}
interface Employee {
employeeId: number;
department: string;
}
type EmployeePerson = Person & Employee;
let employee: EmployeePerson = {
name: "Alice",
age: 30,
employeeId: 1234,
department: "HR"
};
console.log(employee);
// Output: { name: 'Alice', age: 30, employeeId: 1234, department: 'HR' }
Combining Multiple Types
Intersection types can combine more than two types. This is useful for creating complex types that satisfy multiple constraints:
interface Address {
street: string;
city: string;
}
interface Contact {
email: string;
phone: string;
}
type DetailedPerson = Person & Address & Contact;
let detailedPerson: DetailedPerson = {
name: "Bob",
age: 25,
street: "123 Main St",
city: "Somewhere",
email: "bob@example.com",
phone: "123-456-7890"
};
console.log(detailedPerson);
// Output: { name: 'Bob', age: 25, street: '123 Main St', city: 'Somewhere', email: 'bob@example.com', phone: '123-456-7890' }
Using Intersection Types in Functions
Intersection types can be used in function parameters to enforce that a parameter satisfies multiple type constraints:
function printEmployeeInfo(employee: EmployeePerson) {
console.log(`Name: ${employee.name}`);
console.log(`Age: ${employee.age}`);
console.log(`Employee ID: ${employee.employeeId}`);
console.log(`Department: ${employee.department}`);
}
printEmployeeInfo({
name: "Charlie",
age: 28,
employeeId: 5678,
department: "Finance"
});
// Output:
// Name: Charlie
// Age: 28
// Employee ID: 5678
// Department: Finance
Type Guards with Intersection Types
Type guards can be used to narrow down the type of a variable with intersection types:
function printAddressDetails(person: Person & Address) {
console.log(`Address: ${person.street}, ${person.city}`);
}
let personWithAddress: Person & Address = {
name: "Dana",
age: 40,
street: "456 Elm St",
city: "Anywhere"
};
printAddressDetails(personWithAddress);
// Output: Address: 456 Elm St, Anywhere
Conclusion
Intersection types in TypeScript provide a powerful way to combine multiple types into one, allowing you to create complex and precise type definitions. By using intersection types, you can ensure that your variables and function parameters adhere to multiple type constraints, leading to more robust and maintainable code. Understanding how to leverage intersection types effectively can enhance the flexibility and safety of your TypeScript applications.
Comments
Post a Comment