目录

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 };

特点:

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";

要点:

// 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. 常见坑


返回:代码术语