What are TypeScript Union and Intersection Types?
What are TypeScript Union and Intersection Types?
TypeScript is a powerful programming language that extends JavaScript and stands out especially for its type system. In this article, we will explore two important features in TypeScript: Union Types and Intersection Types. First, we will start with a definition of what these types are and how they can be used. Then, we will discuss the advantages of both types.
What are Union Types?
Union Types can be defined as a feature that allows a variable to have more than one type. For example, if you want a variable to be able to take both a number and a string, you can define a Union Type for this variable. Union Types provide flexibility in TypeScript applications and allow developers to write more general code.
Using Union Type
function printId(id: number | string) {
console.log("Your ID is: " + id);
}
printId(101); // Valid
printId("202"); // Valid
In the example above, the printId function can take an id parameter of both number and string types. In this way, valid IDs can be printed both as numeric and as strings.
What are Intersection Types?
Intersection Types allow multiple types to come together to create a new type. This is very useful when an object needs to have properties from multiple interfaces or types. Intersection Types provide strong type safety for developers and can be used to create complex data structures.
Using Intersection Type
interface Employee {
id: number;
name: string;
}
interface Manager {
title: string;
}
type ManagerEmployee = Employee & Manager;
const manager: ManagerEmployee = {
id: 1,
name: "John",
title: "Team Lead"
};
In this example, a type named ManagerEmployee combines both the Employee and Manager interfaces. In this way, we ensure that a manager employee object holds both identity and title information.
Conclusion
Union and Intersection Types in TypeScript allow developers to write more flexible and safer code. Union Types let a variable take values of different types, while Intersection Types allow the combination of multiple types to create more complex data structures. By using these features, you can make your code more readable and maintainable.

Yorum Gönder