In TypeScript, a type alias is a way to create a new name for a type. This can be useful for making your code more readable and manageable, especially when dealing with complex types. Type aliases are defined using the type
keyword followed by the new type name and an assignment to a type expression.
Syntax
type AliasName = Type;
Example of Type Aliases
type StringAlias = string;
type NumberAlias = number;
let myString: StringAlias = "Hello";
let myNumber: NumberAlias = 123;
In this example, StringAlias
is an alias for the string
type, and NumberAlias
is an alias for the number
type.
Union Types
type ID = string | number;
let userId: ID;
userId = "abc"; // OK
userId = 1234567; // OK
Here, ID
is a type alias for the union of string
and number
, making it easier to reuse this type definition.
Object Types
You can also use type aliases to define object types.
type User = {
id: number;
name: string;
email: string;
};
let user: User = {
id: 1,
name: "John Doe",
email: "john.doe@example.com"
};
In this example, User
is a type alias for an object with id
, name
, and email
properties. This makes the code more readable and easier to maintain.
Function Types
Type aliases can be used to define function types as well.
type Operation = (a: number, b: number) => number;
const add: Operation = (x, y) => x + y;
const subtract: Operation = (x, y) => x - y;
console.log(add(10, 4)); // Output: 14
console.log(subtract(10, 4)); // Output: 6
Here, Operation
is a type alias for a function that takes two numbers and returns a number.
Nested Types
You can create type aliases for more complex, nested types.
type Address = {
street: string;
city: string;
country: string;
};
type UserProfile = {
id: number;
name: string;
address: Address;
};
let profile: UserProfile = {
id: 1,
name: "Jane Doe",
address: {
street: "123 Main St",
city: "Anytown",
country: "USA"
}
};
In this example, UserProfile
includes another type alias, Address
, making it easier to manage nested structures.