引用类型
引用类型与原始类型的根本区别在于:原始类型存储的是值本身,引用类型存储的是指向内存中对象的引用。这意味着引用类型的赋值是"引用传递"而非"值传递"。
对象(Object)
字面量对象类型
TypeScript
let obj: {
name: string;
age: number;
sex?: number; // 可选属性
readonly createdAt: Date; // 只读属性
} = {
name: '张三',
age: 18,
createdAt: new Date()
};1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
接口定义(Interface)
接口是TypeScript中定义对象类型的核心方式,它不仅提供类型约束,还能实现代码复用
TypeScript
// 基础接口
interface User {
name: string;
age: number;
role: 'admin' | 'editor' | 'viewer'; // 字面量联合类型
sex?: number;
readonly createdAt: Date;
}
// 接口继承
interface Admin extends User {
role: 'admin'; // 覆盖父类型
managedUsers: number[];
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
TypeScript
// 多重继承
interface Name {
name: string;
}
interface Age {
age: number;
}
interface User extends Name, Age {
gender: string;
}
const user: User = {
name: "张三",
age: 20,
gender: "男"
};1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
索引签名
当对象属性名不确定时,可以使用索引签名来定义对象的属性类型。
TypeScript
// 字符串索引签名
interface User {
[key: string]: any;
}
const user: User = {
name: "张三",
age: 20,
role: "admin",
managedUsers: [1, 2, 3]
};
// 混合索引签名
interface Config {
name: string; // 固定属性
version: string; // 固定属性
[key: string]: string | number; // 动态属性
}
const appConfig: Config = {
name: 'MyApp',
version: '1.0.0',
debug: true, // ❌ 类型错误,boolean不在允许范围内
port: 3000 // ✅
};1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
数组(Array)
两种声明语法
TypeScript
// 字面量语法(推荐)
let arr: number[] = [1, 2, 3];
// 泛型语法
let arr2: Array<number> = [1, 2, 3];1
2
3
4
5
2
3
4
5
只读数组(ReadOnlyArray)
TypeScript
// ReadonlyArray 语法
const colors: ReadonlyArray<string> = ['Red', 'Green', 'Blue'];
// colors.push('Yellow'); // ❌ 类型错误
// readonly 修饰符语法(推荐)
const weekdays: readonly string[] = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
// weekdays[0] = 'Sunday'; // ❌ 类型错误
// const断言(最强约束)
const LANGUAGES = ['TypeScript', 'JavaScript', 'Python'] as const;
// LANGUAGES[0] = 'Rust'; // ❌ 类型错误
// LANGUAGES.push('Go'); // ❌ 类型错误
// 类型推断结果:readonly ['TypeScript', 'JavaScript', 'Python']
// 而非 string[]1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
元组类型
元组是固定长度和固定类型的数组,每个元素的类型可以不同。
TypeScript
// 基础元组
type Point = [number, number];
const coord: Point = [10, 20];
// 带标签的元组(提高可读性)
type HttpResponse = [
status: number,
message: string,
data?: unknown
];
const response: HttpResponse = [200, 'OK', { users: [] }];
// 可选元素元组
type NameAge = [string, number?];
const valid1: NameAge = ['Alice']; // ✅
const valid2: NameAge = ['Bob', 30]; // ✅1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

