第 4 卷
- 类型擦除:移除所有类型信息,编译为纯 JS 代码;
- 生成 JS:输出兼容指定 ES 版本的 JS 代码。
TS 类型系统仅作用于编译阶段,运行时无类型信息,这是与 Java/C# 静态类型的核心区别。
类型推断机制
TS 会自动推导变量/函数的类型,无需手动标注,核心规则:
- 变量初始化推断:
Code block
1let str = "hello"; // 推断为 string 类型 2str = 123; // 报错:不能将 number 赋值给 string
- 函数返回值推断:
Code block
1function add(a: number, b: number) { 2return a + b; // 推断返回值为 number
3} 4const res = add(1, 2); // res 类型为 number
- 上下文推断:根据变量的使用场景推断类型
Code block
1const arr = [1, "hello"]; // 推断为 (string | number)[] 2const obj = { name: "张三", age: 20 }; // 推断为 { name: string; age: number
}
- 泛型类型推断:根据函数参数推断泛型类型
Code block
1function identity<T>(arg: T): T { 2return arg;
3} 4const res = identity("hello"); // 推断 T 为 string
1const arr = [new Date(), new RegExp()]; // 推断为 (Date | RegExp)[]
显式标注 vs 推断:简单类型可依赖推断,复杂类型(如对象、函数参数)建议显式标注,提升可读性。
- 条件类型 (Conditional Types) 是什么?如何使用?
条件类型是 TS 的高级类型,实现“类型层面的三元表达式”,语法为 T extends U ? X : Y (如果 T 是 U 的子类型,返回 X,否则返回 Y)。
基础示例
Code block
1// 基础条件类型:判断类型是否为 string 2type IsString<T> = T extends string ? true : false;
3 4type A = IsString<string>; // true
5type B = IsString<number>; // false
分布式条件类型(核心特性)
当 T 是联合类型时,条件类型会分布式遍历每个成员:
Code block
1type FilterString<T> = T extends string ? T : never;
2 3type C = FilterString<string | number | boolean>; // string(仅保留 string 类型)
内置条件类型
TS 提供了常用的内置条件类型:
- Exclude<T, U>:排除 T 中属于 U 的类型;
- Extract<T, U>:提取 T 中属于 U 的类型;
- ReturnType<T>:获取函数返回值类型;
- Parameters<T>:获取函数参数类型。
4// Extract:提取 5type E = Extract<string | number, number>; // number
6 7// ReturnType:获取函数返回值类型
| 8 | function add(a: number, b: number): number { |
|---|---|
| 9 | return a + b; |
| 10 | } |
| 11 | type F = ReturnType<typeof add>;// number |
12 13// Parameters:获取函数参数类型
14type G = Parameters<typeof add>; // [number, number]
进阶示例(类型过滤)
Code block
1// 过滤对象中值为 string 类型的属性 2type FilterStringProps<T> = {
3[K in keyof T]: T[K] extends string ? K : never;
4}[keyof T];
5 6type User = {
7name: string;
8age: number;
9address: string;
10};
11 12type StringProps = FilterStringProps<User>; // "name" | "address"
- 类型守卫 (Type Guards) 是什么?如何使用?
类型守卫是 TS 的特性,允许在运行时检查类型,缩小类型范围,让编译器识别具体类型,避免类型断言。
常见类型守卫方式
- typeof 类型守卫(检查基本类型):