TypeScript 类型别名与推断
type 关键字与类型推断/断言是 TypeScript 日常编码的基础,下面梳理核心用法。
类型别名
使用 type 为类型创建简短别名:
TypeScript
type ID = string | number;
type Callback = (data: string) => void;
type Point = { x: number; y: number };
const id: ID = "abc123";
const cb: Callback = (data) => console.log(data);
const p: Point = { x: 1, y: 2 };
联合类型别名
TypeScript
type Shape = "circle" | "square" | "triangle";
function draw(shape: Shape) {
console.log(`Drawing ${shape}`);
}
draw("circle"); // ✅
// draw("star"); // ❌ 类型不兼容
交叉类型别名
TypeScript
type WithId = { id: string };
type WithTimestamp = { createdAt: Date };
type Entity = WithId & WithTimestamp;
const entity: Entity = {
id: "1",
createdAt: new Date()
};
类型别名与接口的区别
| 特性 | type | interface |
|---|---|---|
| 扩展语法 | & 交叉 / ` | ` 联合 |
| 声明合并 | ❌ | ✅ |
| 计算属性 | ✅ | ❌ |
建议:对象形状用
interface,联合/交叉/工具类型用type。
类型推断
编译器根据赋值自动推导类型:
TypeScript
let x = 3; // 推断为 number
let name = "Alice"; // 推断为 string
let items = [1, 2]; // 推断为 number[]
函数返回值推断
TypeScript
function add(a: number, b: number) {
return a + b; // 推断返回值为 number
}
上下文类型推断
TypeScript
window.onmousedown = function (e) {
// e 自动推断为 MouseEvent
console.log(e.clientX);
};
注意:当变量声明但未赋值时,推断为
any(strict 模式下为编译错误)。
类型断言
使用 as 手动指定类型,覆盖编译器推断:
TypeScript
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;
DOM 元素断言
TypeScript
const canvas = document.getElementById("myCanvas") as HTMLCanvasElement;
canvas.width = 800;
注意:类型断言不做运行时检查,仅是编译期提示,断言错误可能导致运行时异常。
非空断言
使用 ! 告诉编译器值不为 null/undefined:
TypeScript
function getValue(): string | null {
return "hello";
}
const val = getValue()!; // 断言不为 null,类型为 string
const 断言
使用 as const 创建字面量只读类型:
TypeScript
let x = "hello"; // 类型:string
let y = "hello" as const; // 类型:"hello"
let arr = [10, 20] as const; // 类型:readonly [10, 20]
let obj = { name: "TS" } as const;
// obj.name = "JS"; // ❌ 只读
要点总结
type创建类型别名,支持联合/交叉/工具类型- 编译器根据赋值自动推断类型,减少冗余注解
as断言手动指定类型,!非空断言,as const字面量只读- 断言不做运行时检查,使用需谨慎
- 日常编码优先让编译器推断,仅在必要时使用断言
📝 发现内容有误?点击此处直接编辑