TypeScript type alias

A type alias is used to create an alias for an existing type, making code cleaner and easier to read.

With type aliases, you can define a short name for complex types, improving code maintainability.


SVG diagram: type alias Background Title How type aliases work Original type Original complex type type User = { name: string; age: number; email: string; } Arrow Definition type alias type alias type UserID = User; // or type ID = string | number; Arrow Usage Usage Use in code var id: UserID; var uid: ID; Lower part: application scenarios Application scenarios for type aliases Scenario 1 Basic type alias Scenario 2 Union type alias Scenario 3 Function type alias Scenario 4 Generic type alias Arrow marker

Why do we need type aliases

When the same complex type is used many times in code, writing the full type each time becomes verbose.

Type aliases can define a concise name for complex types, making code more readable and maintainable.

Type aliases are especially useful when working with complex types such as union types, function types, and tuples.

Concept explanation:Type alias usagetypedefined with the `type` keyword; it simply gives an existing type a new name and does not create a new type.


Basic usage

Use the `type` keyword to define an alias for a type.

Example

// Type alias: define an alias for a union type
// ID can be a string or a number
type ID = string | number;

// Type alias: define an alias for an object type
// Point represents a coordinate point
type Point = { x: number; y: number };

// Use the type alias
var userId: ID = "123";
var productId: ID = 456;

// Use the Point type alias
var point: Point = { x: 10, y: 20 };

console.log("User ID: " + userId);
console.log("Product ID: " + productId);
console.log("Coordinates: " + JSON.stringify(point));

Output:

用户ID: 123
产品ID: 456
坐标: {"x":10,"y":20}

Explanation:A type alias just gives a type a new name; it generates no actual code after compilation and is used entirely for type checking during development.


Interface vs type alias

Type aliases and interfaces are very similar; both can be used to define object types, but there are some subtle differences.

Example

// Use a type alias to define an object type
// type can define any type, not just objects
type PersonType = {
    name: string;
    age: number;
};

// Use an interface to define an object type
// Interfaces support declaration merging and can be implemented by classes
interface PersonInterface {
    name: string;
    age: number;
}

// Both can be used to declare variable types
var person1: PersonType = { name: "Alice", age: 25 };
var person2: PersonInterface = { name: "Bob", age: 30 };

console.log("PersonType: " + JSON.stringify(person1));
console.log("PersonInterface: " + JSON.stringify(person2));

Differences:type can define any type (union types, tuples, function types, etc.), while interfaces are mainly used for object types. Interfaces support declaration merging, but type does not.


Type aliases and union types

Type aliases are perfect for defining union types, making code clearer.

Example

// Union type alias: define possible values for a status
// Status can only be one of these three string literals
type Status = "pending" | "success" | "error";

// Union type alias: define multiple possible return types
// Result can be a string, number, or boolean
type Result = string | number | boolean;

// Use the union type alias
function getStatus(status: Status): void {
    console.log("Status: " + status);
}

getStatus("success");
getStatus("error");

// Use the Result type
var result: Result = "hello";
result = 42;
console.log("Result: " + result);

Output:

Status: success
Status: error
结果: 42

Application scenarios:Union type aliases are often used to define status codes, error types, API return values, and similar scenarios.


Type aliases and tuples

Type aliases can also be used to define tuple types.

Example

// Tuple type alias: define coordinates
// Coordinate is a tuple containing two numbers
type Coordinate = [number, number];

// Tuple type alias: define name and age
// NameAge is a tuple of a string and a number
type NameAge = [string, number];

// Use the tuple type alias
var coord: Coordinate = [10, 20];
var person: NameAge = ["Alice", 25];

console.log("Coordinates: " + coord);
console.log("Info: " + person[0] + ", " + person[1]);

Explanation:Tuple type aliases make tuple usage clearer and avoid the need to write out the full tuple type every time.


Type aliases and functions

Type aliases can simplify function type declarations.

Example

// Function type alias: define a callback function type
// Callback takes a string parameter and returns void
type Callback = (result: string) => void;

// Function type alias: define a math operation function type
// MathOperation takes two number parameters and returns a number
type MathOperation = (a: number, b: number) => number;

// Use the function type alias
var add: MathOperation = function(a, b) { return a + b; };
var multiply: MathOperation = function(a, b) { return a * b; };

console.log("Addition: " + add(2, 3));
console.log("Multiplication: " + multiply(4, 5));

Output:

加法: 5
乘法: 20

Advantages:Function type aliases make function type declarations more concise, especially when the same function signature is needed multiple times.


Type aliases and generics

Type aliases can be used with generics to create reusable type definitions.

Example

// Generic type alias: define a result type
// Result<T> is a generic type; T is the data type on success
type Result<T> = { success: boolean; data?: T; error?: string };

// Generic type alias: define a key-value pair type
// Pair<K, V> has two type parameters
type Pair<K, V> = { key: K; value: V };

// Use the generic type alias
var result: Result<string> = { success: true, data: "Hello" };
var pair: Pair<string, number> = { key: "age", value: 25 };

console.log("Result: " + JSON.stringify(result));
console.log("Key-value pair: " + JSON.stringify(pair));

Output:

结果: {"success":true,"data":"Hello"}
键值对: {"key":"age","value":25}

Generic advantages:Generic type aliases can adapt to different data types, improving code reusability.


Type aliases and mapped types

Type aliases can be combined with mapped types to create powerful type transformations.

Example

// Mapped type: make all properties readonly
// Readonly<T> iterates over all properties of T and adds readonly
type Readonly<T> = { readonly [P in keyof T]: T[P] };

// Mapped type: make all properties optional
// Partial<T> iterates over all properties of T and adds ?
type Partial<T> = { [P in keyof T]?: T[P] };

// Define a user interface
interface User {
    name: string;
    age: number;
}

// Use mapped type aliases
var readonlyUser: Readonly<User> = { name: "Alice", age: 25 };
// readonlyUser.name = "Bob"; // Error: readonly property cannot be modified

var partialUser: Partial<User> = { name: "Bob" };

console.log("Readonly user: " + JSON.stringify(readonlyUser));
console.log("Partial user: " + JSON.stringify(partialUser));

Tip:Mapped types are a very powerful feature of TypeScript, allowing you to create new type variations based on existing types.


Notes

  • Cannot be redefined:The same type alias cannot be redefined (interfaces can be declaration-merged)
  • Only valid at compile time:Type aliases produce no code after compilation
  • Readability first:Do not overuse type aliases; concise and clear code is better

Best practices:Use type aliases when a type needs to be reused or when the type name is too long. For simple object types, you can choose type or interface based on your team's preferences.


Summary

Type aliases are a very useful feature in TypeScript.

  • Basic usage:Use the `type` keyword to define an alias for complex types
  • Union types:Define combinations of multiple possible types
  • Function types:Simplify function type declarations
  • Generics:Create reusable generic types
  • Mapped types:Create new types based on existing types

Recommendation:Using type aliases appropriately can make code clearer, but don't overuse them. Keeping code concise and readable is what matters most.

Other extensions