Introduction
In this chapter, we will explore type aliases in TypeScript. Type aliases allow you to create a new name for a type. This can be useful for simplifying complex types, improving code readability, and reusing type definitions. Understanding how to use type aliases is essential for managing and organizing types in your TypeScript programs.
Table of Contents
- Definition
- Creating Type Aliases
- Using Type Aliases
- Type Aliases for Unions and Intersections
- Recursive Type Aliases
- Complete Example with Output
- Conclusion
Definition
A type alias in TypeScript is a name that you can create for a type. This allows you to give a meaningful name to a type and reuse it throughout your code. Type aliases can be used for any type, including primitive types, object types, union types, intersection types, and function types.
Creating Type Aliases
You can create a type alias using the type
keyword followed by the alias name and the type it represents.
Syntax
type AliasName = Type;
Example
type StringAlias = string;
type NumberAlias = number;
let message: StringAlias = "Hello, TypeScript!";
let age: NumberAlias = 25;
console.log(message, age);
Output
Hello, TypeScript! 25
Using Type Aliases
Type aliases can be used in variable declarations, function parameters, return types, and object properties.
Example
type ID = number | string;
let userId: ID = 123;
console.log(userId); // Output: 123
userId = "ABC123";
console.log(userId); // Output: ABC123
function printId(id: ID): void {
console.log(`The ID is ${id}`);
}
printId(456); // Output: The ID is 456
printId("XYZ456"); // Output: The ID is XYZ456
Output
123
ABC123
The ID is 456
The ID is XYZ456
Type Aliases for Unions and Intersections
Type aliases are especially useful for union and intersection types, which can be complex and verbose.
Example
type SuccessResponse = {
status: "success";
data: string;
};
type ErrorResponse = {
status: "error";
message: string;
};
type APIResponse = SuccessResponse | ErrorResponse;
function handleResponse(response: APIResponse): void {
if (response.status === "success") {
console.log(`Data: ${response.data}`);
} else {
console.log(`Error: ${response.message}`);
}
}
const success: APIResponse = { status: "success", data: "User created successfully" };
const error: APIResponse = { status: "error", message: "Failed to create user" };
handleResponse(success); // Output: Data: User created successfully
handleResponse(error); // Output: Error: Failed to create user
Output
Data: User created successfully
Error: Failed to create user
Recursive Type Aliases
Type aliases can also be recursive, allowing you to define types that reference themselves. This is useful for defining tree structures or nested data.
Example
type TreeNode = {
value: number;
left?: TreeNode;
right?: TreeNode;
};
const tree: TreeNode = {
value: 1,
left: {
value: 2,
left: { value: 4 },
right: { value: 5 }
},
right: {
value: 3
}
};
function traverseTree(node: TreeNode): void {
console.log(node.value);
if (node.left) traverseTree(node.left);
if (node.right) traverseTree(node.right);
}
traverseTree(tree); // Output: 1 2 4 5 3
Output
1
2
4
5
3
Complete Example with Output
In this section, we will combine all the examples into a single TypeScript file, compile it to JavaScript, and run it to see the output.
TypeScript Code
You can test the following code in the TypeScript Playground:
// Creating Type Aliases
type StringAlias = string;
type NumberAlias = number;
let message: StringAlias = "Hello, TypeScript!";
let age: NumberAlias = 25;
console.log(message, age); // Output: Hello, TypeScript! 25
// Using Type Aliases
type ID = number | string;
let userId: ID = 123;
console.log(userId); // Output: 123
userId = "ABC123";
console.log(userId); // Output: ABC123
function printId(id: ID): void {
console.log(`The ID is ${id}`);
}
printId(456); // Output: The ID is 456
printId("XYZ456"); // Output: The ID is XYZ456
// Type Aliases for Unions and Intersections
type SuccessResponse = {
status: "success";
data: string;
};
type ErrorResponse = {
status: "error";
message: string;
};
type APIResponse = SuccessResponse | ErrorResponse;
function handleResponse(response: APIResponse): void {
if (response.status === "success") {
console.log(`Data: ${response.data}`);
} else {
console.log(`Error: ${response.message}`);
}
}
const success: APIResponse = { status: "success", data: "User created successfully" };
const error: APIResponse = { status: "error", message: "Failed to create user" };
handleResponse(success); // Output: Data: User created successfully
handleResponse(error); // Output: Error: Failed to create user
// Recursive Type Aliases
type TreeNode = {
value: number;
left?: TreeNode;
right?: TreeNode;
};
const tree: TreeNode = {
value: 1,
left: {
value: 2,
left: { value: 4 },
right: { value: 5 }
},
right: {
value: 3
}
};
function traverseTree(node: TreeNode): void {
console.log(node.value);
if (node.left) traverseTree(node.left);
if (node.right) traverseTree(node.right);
}
traverseTree(tree); // Output: 1 2 4 5 3
Conclusion
In this chapter, we covered type aliases in TypeScript, including how to create and use them to simplify complex types, improve code readability, and reuse type definitions. We also explored how to use type aliases for union and intersection types, and how to create recursive type aliases. We provided a complete example with its output to illustrate how type aliases work in TypeScript.
Comments
Post a Comment
Leave Comment