alias(别名)
alias(别名) 就是“给已经存在的某个东西起的另一个名字”。在 TypeScript 代码里,这个词出现在三个完全不同的场景,含义也不一样:类型别名、导入/导出别名、路径别名。
1. 类型别名(type alias)
用 type 给一个类型起名字,之后就能当类型使用。
type UserId = string | number; // 联合类型
type Point = { x: number; y: number }; // 对象结构
type Handler = (e: Event) => void; // 函数类型
type Pair = [number, number]; // 元组
type Status = "idle" | "loading" | "done"; // 字面量联合,常用于状态机
const id: UserId = 123;
const p: Point = { x: 1, y: 2 };
特点:
- 只是起名字,不产生新类型,编译后完全消失(零运行时开销)
- 能描述任意类型:联合、交叉、元组、原始类型、泛型都可以
- 不能同名声明合并,重复写两个同名
type会报错
2. 导入 / 导出别名(''as'' 重命名)
// 导入时改名,常用于解决命名冲突
import { createUser as addUser } from "./user";
import { createUser as createAdminUser } from "./admin";
// 命名空间导入
import * as utils from "./utils";
// 导出时改名
export { internalImpl as publicApi };
// 默认导入同样可以起任意本地名字
import MyComponent from "./MyComponent";
要注意:as 在类型断言里(value as string)与别名无关,那是“断言”不是“改名”。
3. 路径别名(模块解析别名)
让 @/xxx 这类短路径代替 ../../xxx 这种相对路径。
// tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
import { Button } from "@/components/Button";
要点:
tsconfig的paths只影响类型检查,不会改写运行时真正加载的模块路径- 运行时还要打包工具配合,否则报 “Cannot find module”:
- Vite:
resolve.alias - webpack:
resolve.alias - Node 直接跑 TS:
tsconfig-paths或在打包器里处理
// vite.config.ts
import { defineConfig } from "vite";
import path from "path";
export default defineConfig({
resolve: {
alias: { "@": path.resolve(__dirname, "src") }
}
});
4. ''type'' 别名与 ''interface'' 的对比
| 对比项 | type | interface |
|---|---|---|
| 描述对象结构 | 可以 | 可以(更常用) |
| 联合 / 元组 / 原始类型 | 可以 | 不可以 |
| 同名声明合并 | 不可以 | 可以 |
| 扩展方式 | 交叉类型 A & B | extends |
| 编译后产物 | 消失 | 消失 |
经验:描述对象、需要扩展或声明合并时用 interface;联合类型、元组、函数类型、给复杂类型起个短名字时用 type。
5. 常见坑
- 配了路径别名却忘了打包工具 → 编译通过、运行时报
Cannot find module - 想给第三方类型“打补丁”(声明合并)只能用
interface,type做不到 - 别名不改变类型本质:
type A = string中A和string完全互相兼容,不会带来额外的类型安全 - 别名满天飞会让人找不到定义,公共别名建议集中放在
types.ts里统一维护
返回:代码术语