ZetCode

TypeScript type 关键字

最后修改于 2025 年 2 月 25 日

TypeScript 中的 type 关键字用于创建自定义类型或类型别名。它允许你定义可重用且复杂的类型,使你的代码更具可读性和可维护性。本教程通过实际示例涵盖了 type 关键字的用法。

type 关键字用于创建类型别名,它们是现有类型或类型组合的自定义名称。类型别名可以表示基本类型、对象类型、联合类型、交叉类型等。它们不创建新类型,而是提供了一种使用自定义名称引用现有类型的方式。

创建基本类型别名

此示例演示了如何为基本类型创建类型别名。

basic_type_alias.ts
type Age = number;

let userAge: Age = 25;
console.log(userAge);  // Output: 25

Age 类型别名是为 number 类型创建的。这提高了代码的可读性,并在需要更新类型时方便进行更改。

创建对象类型别名

此示例演示了如何为对象类型创建类型别名。

object_type_alias.ts
type User = {
    name: string;
    age: number;
    isActive: boolean;
};

let user: User = {
    name: "Alice",
    age: 30,
    isActive: true
};

console.log(user);  // Output: { name: "Alice", age: 30, isActive: true }

User 类型别名定义了一个具有特定属性的对象的结构。这使得定义和重用用户对象的结构更加容易。

创建联合类型别名

此示例演示了如何为联合类型创建类型别名。

union_type_alias.ts
type ID = string | number;

let userId: ID = "12345";
let productId: ID = 67890;

console.log(userId);    // Output: 12345
console.log(productId); // Output: 67890

ID 类型别名是为可以是 stringnumber 的联合类型创建的。这允许灵活的类型定义。

创建函数类型别名

此示例演示了如何为函数类型创建类型别名。

function_type_alias.ts
type GreetFunction = (name: string) => string;

let greet: GreetFunction = (name) => {
    return `Hello, ${name}!`;
};

console.log(greet("Alice"));  // Output: Hello, Alice!

GreetFunction 类型别名定义了一个函数类型,该函数接受一个 string 参数并返回一个 string。这使得定义和使用具有相同签名的函数更加容易。

创建元组类型别名

此示例演示了如何为元组类型创建类型别名。

tuple_type_alias.ts
type Point = [number, number];

let coordinates: Point = [10, 20];
console.log(coordinates);  // Output: [10, 20]

Point 类型别名定义了一个元组类型,该类型表示一对数字。这使得处理坐标对或类似数据结构更加容易。

创建交叉类型别名

此示例演示了如何为交叉类型创建类型别名。

intersection_type_alias.ts
type Person = {
    name: string;
    age: number;
};

type Employee = {
    employeeId: number;
};

type EmployeeDetails = Person & Employee;

let employee: EmployeeDetails = {
    name: "Alice",
    age: 30,
    employeeId: 12345
};

console.log(employee);  // Output: { name: "Alice", age: 30, employeeId: 12345 }

EmployeeDetails 类型别名使用交叉运算符(&)组合了 PersonEmployee 类型。这允许你创建一个包含来自这两种类型的所有属性的新类型。

使用 type 关键字的最佳实践

来源

type 关键字文档

在本文中,我们探讨了 TypeScript 的 type 关键字,并通过实际示例演示了其用法。

作者

我的名字是 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 TypeScript 教程