TypeScript Type Aliases
TypeScript provides a powerful way to define custom types using type aliases. Type aliases allow you to create a new name for a type, which can be a primitive, union, intersection, tuple, or any other valid TypeScript type. This can make your code more readable and maintainable.
Defining a Type Alias
To define a type alias, use the type
keyword followed by the alias name and the type definition:
type StringAlias = string;
type NumberAlias = number;
type BooleanAlias = boolean;
Using type aliases
Once you have defined a type alias, you can use it to declare variables, function parameters, return types, and more:
type UserID = string;
let UserId: UserID = "abcd12345";
Complex Type Aliases
Type aliases can also be used to define more complex types such as unions, intersections, tuples, and generics:
Object Type Alias
type User = {
id: number;
name: string;
email: string;
}
let user: User = {
id: 1,
name: "Pratap Das",
email: "pratap.das@gmail.com"
}
Union Type Alias
type Status = "active" | "inactive" | "pending";
let currentStatus: Status = "active";
// or
type Status = "success" | "error" | "loading";
let currentStatus: Status = "loading";
Intersection Type Alias
type Person = {
name: string;
}
type Employee = {
employeeId: number;
department: string;
}
let employee: Person & Employee = {
name: "Prata Das",
id: 999,
department: "Engineering"
}
Tuple Type Alias
type Point = [number, number];
let point: Point = [10, 20];
Advantages of Type Aliases
- Readability: Type aliases make your code more readable by giving meaningful names to types.
- Maintainability: Type aliases help in maintaining consistency across your codebase by defining types in a single place.
- Reusability: Type aliases can be reused across multiple parts of your codebase, reducing duplication.
Type aliases are a versatile feature in TypeScript that can help you write cleaner and more maintainable code. Use them to simplify your type definitions and improve the readability of your code.