类型 Aliases in TypeScript
如何 创建 named 类型 aliases for primitives, unions, 对象, and 函数 signatures.
你将学到
- 如何 定义类型 alias 使用类型 keyword
- difference 之间类型 aliases and 接口
- Using aliases for union 类型 and 函数 signatures
- 当到 选择类型 alias over 接口
概念讲解
Creating Named Types
A type alias gives a name to any type using the 类型 keyword: 类型 ID = 数字 | 字符串;. Unlike interfaces, which only describe object shapes, type aliases can name primitives, unions, intersections, tuples, and function signatures. This makes them more flexible for non-object types. For example, 类型 回调 = (错误: 错误 | 空, result?: 任何) => 空 names a common callback pattern.
Type Aliases vs Interfaces
Interfaces and type aliases are very similar for object types — both can describe object shapes, both can be extended (interfaces via extends, aliases via intersection &). The key differences: interfaces can be merged (re-declaration combines members), while type aliases cannot. Type aliases can express unions and primitives, while interfaces cannot. Use interfaces for object shapes that might be extended, and aliases for unions, primitives, and function types.
Practical Usage
Type aliases shine for naming union types (类型 状态 = "active" | "inactive" | "pending"), tuple types (类型 点 = [数字, 数字]), and function signatures (类型 处理函数 = (事件: 事件) => 空). They make code self-documenting by giving meaningful names to complex types, and they are essential for building the advanced type patterns covered later in this course.
示例代码
// Type alias for a union of string literals (string literal type).
type Status = "active" | "inactive" | "pending";
// Type alias for a tuple.
type Point = [number, number];
// Type alias for a function signature.
type Handler = (event: string) => void;
// Type alias for an object shape (similar to interface).
type User = {
id: number;
name: string;
status: Status;
};
const user: User = { id: 1, name: "Alice", status: "active" };
const origin: Point = [0, 0];
const logHandler: Handler = (event) => console.log(event);
logHandler(user.status);
类型 aliases name 任何类型: unions, tuples, 函数, and 对象. Use 它们 for 非-对象类型 and unions; use 接口 for extensible 对象 shapes.
动手试一试
- JSON 到 TypeScript
Generated 输出经常 uses 类型 aliases for union and tuple 类型.
- Markdown Previewer
Document 你的类型 aliases 使用 readable Markdown.
常见错误
错误写法
Using 类型 alias 当接口 extension or 合并是 需要
正确做法
接口 support declaration 合并 and extends. 如果你 需要到 组合定义跨越 files, use 接口相反的 类型 alias.
错误写法
Thinking 类型 and 接口是 completely interchangeable
正确做法
它们是 nearly identical for 对象, 但仅 类型 aliases 能 express unions, primitives, and tuples. 选择 based on 什么你 是 naming.
练习 类型 Aliases in TypeScript
6 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。