TypeScript 学习指南
📚 目录
一、基础类型与变量
1. 基本类型
概念说明:
TypeScript 拥有丰富的基础类型:number、string、boolean、array、tuple、enum、any、void、null、undefined、never 和 unknown 等。
number:表示所有数字,包括整数和浮点数。如:let n: number = 42;string:字符串类型,表示文本数据。如:let s: string = "hello";boolean:布尔类型,只能是true或false。如:let flag: boolean = true;array:数组类型,同类型元素的有序集合。如:let arr: number[] = [1, 2, 3];tuple(元组):固定长度、各元素类型可不同的数组。如:let pair: [string, number] = ['foo', 1];enum:枚举类型,用于定义一组命名常量。如:enum Color { Red, Green, Blue, } let c: Color = Color.Green;any:任意类型,关闭类型检查,谨慎使用。如:let anything: any = 123;void:通常用于函数无返回值。function log(): void { console.log('hi'); }null和undefined:分别表示空值和未定义。可以赋给任意类型,但需要严格模式下注意区别。never:表示不会有值的类型,如函数抛异常或死循环时的返回值:function error(msg: string): never { throw new Error(msg); }unknown:类型安全的any,只能经过类型检查后才能赋值给其他类型。用于安全接收不确定类型的数据。let value: unknown = 123; if (typeof value === 'string') { console.log(value.length); // 类型收窄后才能访问 string 的属性 }
TypeScript 默认为严格区分 null 和 undefined,配置项 strictNullChecks 开启时变量不会默认包含这两者,需单独指定。
2. 类型别名与接口
概念说明:
- 类型别名(
type)可以为任何类型(基本类型、联合、对象、元组等)起别名。 - 接口(
interface)主要用于描述对象、函数、类的结构。
类型别名(type)与接口(interface)对比:
| type | interface | |
|---|---|---|
| 定义对象类型 | ✅ | ✅ |
| 定义基本/联合/元组类型 | ✅ | ❌(只能描述对象、类、函数结构) |
| 扩展(继承) | 通过 & 交叉类型合成 | extends 关键字继承、交叉合成 |
| 重新打开/声明合并 | ❌(不可重复定义) | ✅(多次声明自动合并同名 interface) |
| 实现类 | ❌ | ✅(class implements interface) |
| 推荐场景 | 复杂类型、组合类型、多种类型联合 | 主要用于对象结构、面向对象接口 |
使用建议: 对象结构建议优先用 interface,涉及联合、交叉或基础类型的组合、类型工具一般用 type。
简单对比代码:
使用 type
// 使用 type
type PointOrId = { x: number; y: number } | number;
type Name = string;
使用 interface
// 定义Person
interface Person {
name: string;
age: number;
}
// 合并接口
interface Person {
gender?: string;
}
const tom: Person = { name: 'Tom', age: 20, gender: 'male' };
// 接口可继承
interface Student extends Person {
studentId: number;
}
const alice: Student = {
name: 'Alice',
age: 21,
gender: 'female',
studentId: 1001,
};
// 实现类
class Teacher implements Person {
name: string;
age: number;
gender?: string;
subject: string;
constructor(name: string, age: number, subject: string, gender?: string) {
this.name = name;
this.age = age;
this.subject = subject;
if (gender) {
this.gender = gender;
}
}
}
const msSmith = new Teacher('Smith', 35, 'Math', 'female');
二、类型系统核心能力
3. 联合类型(Union Types)
概念说明:
联合类型用 | 分隔,表示一个值可以是多种类型之一,对应多种可能取值场景。
示例:
function printId(id: string | number) {
if (typeof id === 'string') {
console.log(id.toUpperCase());
} else {
console.log(id);
}
}
4. 交叉类型(Intersection Types)
概念说明:
交叉类型用 &,把多个类型的所有特性组合在一起(多重继承)。
示例:
type Person = { name: string };
type Employee = { id: number };
type Staff = Person & Employee;
let staff: Staff = { name: 'Mike', id: 101 };
5. 类型推断与类型断言
类型推断
TypeScript 能自动推断变量类型。
类型断言
类型断言用于确定变量的具体类型(通常用 as)。有时候你比 TypeScript 更了解某个值的类型,可以使用类型断言。
示例:
let num = 4; // 推断为 number
let someValue: any = 'some text';
let len: number = (someValue as string).length;
6. 映射类型(Mapped Types)
概念说明:
映射类型可对已有类型做结构变换,自动化构造新类型结构(如批量只读、可选)。
示例:
type Readonly<T> = {
readonly [K in keyof T]: T[K];
};
type Person = { name: string; age: number };
type ReadonlyPerson = Readonly<Person>; // name、age只读
7. 条件类型与 infer
概念说明:
- 条件类型允许根据类型逻辑做分支推导。
infer可在条件类型内做类型局部推断。
示例:
type IsString<T> = T extends string ? true : false;
type A = IsString<'abc'>; // true
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
function fn(x: number): string {
return x.toString();
}
type FnReturn = ReturnType<typeof fn>; // string
8. 类型守卫(Type Guards)
概念说明:
类型守卫让类型缩小到更具体的类型,提升类型安全性(典型如 typeof、instanceof、自定义守卫函数)。
示例:
function isString(value: unknown): value is string {
return typeof value === 'string';
}
function example(val: string | number) {
if (isString(val)) {
// val 被收窄为 string
console.log(val.toUpperCase());
}
}
function printId(id: string | number) {
if (typeof id === 'string') {
console.log('String id:', id.toUpperCase());
} else {
console.log('Number id:', id);
}
}
三、泛型与高级类型工具
9. 泛型(Generics)& 索引签名(Index Signature)
泛型:
泛型为类型参数化,允许类型灵活支持多种场景。
示例:
function identity<T>(arg: T): T {
return arg;
}
let num = identity<number>(1); // num: number
let txt = identity<string>('hi'); // txt: string
索引签名: 索引签名用于定义对象可以有任意数量的某种类型的属性名和值。
示例:
interface StringMap {
[key: string]: string;
}
const dict: StringMap = {
hello: '你好',
world: '世界',
};
你也可以限定值为其它类型,并且 number 形式的索引会被转为 string:
interface NumberMap {
[key: number]: boolean;
}
const status: NumberMap = {
1: true,
2: false,
};
// 实际等价于 { '1': true, '2': false }
10. 常用泛型工具类型
概念说明: TypeScript 标准库内置多种泛型类型工具,极大增强类型复用性和便捷性。
Partial<T>:所有属性变为可选Required<T>:所有属性变为必填Readonly<T>:所有属性只读Pick<T, K>:保留指定属性Omit<T, K>:去除指定属性Record<K,T>:构造以 K 为键、T 为值的对象类型Exclude<T,U>、Extract<T,U>:类型差集、交集NonNullable<T>:排除 null、undefined
示例:
interface User {
id: number;
name: string;
age?: number;
}
type PartialUser = Partial<User>; // 所有属性可选
// { id?: number; name?: string; age?: number; }
type RequiredUser = Required<User>; // 所有属性必填
// { id: number; name: string; age: number; }
type ReadonlyUser = Readonly<User>; // 所有属性只读
// { readonly id: number; readonly name: string; readonly age?: number; }
type UserIdAndName = Pick<User, 'id' | 'name'>; // 只保留 id 和 name
// { id: number; name: string; }
type UserWithoutAge = Omit<User, 'age'>; // 去掉 age 属性
// { id: number; name: string; }
type UserMap = Record<string, User>; // 以字符串为 key 的 User 对象集合
四、应用进阶
11. 字符串字面量类型与模板字面量类型
概念说明:
允许“类型”层面限制/组合字符串,强化类型表达能力。
示例:
type Direction = 'up' | 'down' | 'left' | 'right';
type Size = 'small' | 'medium' | 'large';
// 模板字面量类型
type EventName = `on${Capitalize<string>}`;
12. 可辨识联合与索引类型
可辨识联合
通过共同的字面量字段做类型分支判定。
示例:
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; side: number };
function area(shape: Shape): number {
if (shape.kind === 'circle') {
return Math.PI * shape.radius ** 2;
}
return shape.side ** 2;
}
索引类型
利用 keyof 提取类型的 key 集合,T[K] 访问属性类型。
示例:
type Point = { x: number; y: number };
type PointKeys = keyof Point; // "x" | "y"
type XType = Point['x']; // number
13. this 类型与流式接口
解释:
在方法内部返回 this,可以实现链式调用风格。
示例:
class Counter {
count = 0;
increment(): this {
this.count++;
return this;
}
}
const c = new Counter();
c.increment().increment();
14. 可选链与空值合并运算符
概念说明:
?.可安全访问嵌套属性??可提供默认值
示例:
const obj = { foo: { bar: 42 } };
const val = obj.foo?.bar; // 42
const def = obj.baz?.qux ?? 'default'; // "default"
五、总结学习建议
TypeScript 类型系统强大且灵活,涵盖如联合、交叉、映射、条件、工具类型等多样特性。熟练掌握这些基础与高阶用法,将显著提升代码的类型安全、复用性与开发效率。日常建议通过不断实践、灵活组合使用类型能力,逐步突破更复杂的类型场景。