TypeScript对象类型 #
一、对象类型基础 #
1.1 什么是对象类型 #
对象类型是TypeScript中最常用的类型之一,用于描述对象的结构。
typescript
function greet(person: { name: string; age: number }): string {
return `Hello, ${person.name}!`;
}
greet({ name: 'Alice', age: 25 });
1.2 对象类型的定义方式 #
内联类型 #
typescript
function printCoord(coord: { x: number; y: number }): void {
console.log(`(${coord.x}, ${coord.y})`);
}
接口 #
typescript
interface Point {
x: number;
y: number;
}
function printCoord(coord: Point): void {
console.log(`(${coord.x}, ${coord.y})`);
}
类型别名 #
typescript
type Point = {
x: number;
y: number;
};
function printCoord(coord: Point): void {
console.log(`(${coord.x}, ${coord.y})`);
}
二、属性类型 #
2.1 必需属性 #
typescript
interface User {
name: string;
age: number;
}
const user: User = {
name: 'Alice',
age: 25
};
2.2 可选属性 #
使用?标记可选属性:
typescript
interface User {
name: string;
age?: number;
email?: string;
}
const user1: User = { name: 'Alice' };
const user2: User = { name: 'Bob', age: 30 };
const user3: User = { name: 'Charlie', age: 25, email: 'charlie@example.com' };
2.3 只读属性 #
使用readonly标记只读属性:
typescript
interface User {
readonly id: number;
name: string;
}
const user: User = {
id: 1,
name: 'Alice'
};
user.id = 2;
user.name = 'Bob';
2.4 readonly vs const #
readonly用于属性const用于变量
typescript
const user = {
name: 'Alice'
} as const;
user.name = 'Bob';
三、索引签名 #
3.1 字符串索引签名 #
typescript
interface StringMap {
[key: string]: string;
}
const map: StringMap = {
name: 'TypeScript',
version: '5.4'
};
3.2 数字索引签名 #
typescript
interface NumberArray {
[index: number]: string;
}
const arr: NumberArray = ['a', 'b', 'c'];
console.log(arr[0]);
3.3 混合索引签名 #
typescript
interface Dictionary {
[key: string]: string | number;
length: number;
name: string;
}
const dict: Dictionary = {
length: 3,
name: 'My Dictionary',
key1: 'value1',
key2: 'value2'
};
3.4 只读索引签名 #
typescript
interface ReadonlyStringMap {
readonly [key: string]: string;
}
const map: ReadonlyStringMap = {
name: 'TypeScript'
};
map.name = 'JavaScript';
四、方法类型 #
4.1 方法定义 #
typescript
interface Calculator {
add(a: number, b: number): number;
subtract(a: number, b: number): number;
}
const calc: Calculator = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
4.2 方法简写 #
typescript
interface Logger {
log(message: string): void;
error(message: string): void;
}
const logger: Logger = {
log(message) {
console.log(`[LOG] ${message}`);
},
error(message) {
console.error(`[ERROR] ${message}`);
}
};
4.3 可选方法 #
typescript
interface Handler {
onSuccess?(): void;
onError?(error: Error): void;
}
const handler: Handler = {
onSuccess() {
console.log('Success');
}
};
五、可调用类型 #
5.1 调用签名 #
typescript
interface Add {
(a: number, b: number): number;
}
const add: Add = (a, b) => a + b;
5.2 构造签名 #
typescript
interface AnimalConstructor {
new (name: string): Animal;
}
interface Animal {
name: string;
}
function createAnimal(ctor: AnimalConstructor, name: string): Animal {
return new ctor(name);
}
5.3 混合类型 #
typescript
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
const counter = function (start: number) {
return `Started at ${start}`;
} as Counter;
counter.interval = 100;
counter.reset = function () {
console.log('Reset');
};
return counter;
}
六、对象类型操作 #
6.1 合并对象类型 #
typescript
type Name = { name: string };
type Age = { age: number };
type Person = Name & Age;
const person: Person = {
name: 'Alice',
age: 25
};
6.2 扩展对象类型 #
typescript
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
const dog: Dog = {
name: 'Max',
breed: 'Golden Retriever'
};
6.3 部分属性 #
typescript
interface User {
name: string;
age: number;
email: string;
}
type PartialUser = Partial<User>;
const partial: PartialUser = {
name: 'Alice'
};
6.4 必需属性 #
typescript
interface User {
name: string;
age?: number;
email?: string;
}
type RequiredUser = Required<User>;
const required: RequiredUser = {
name: 'Alice',
age: 25,
email: 'alice@example.com'
};
七、类型兼容性 #
7.1 结构化类型 #
TypeScript使用结构化类型系统(鸭子类型):
typescript
interface Point {
x: number;
y: number;
}
function printPoint(point: Point): void {
console.log(`(${point.x}, ${point.y})`);
}
printPoint({ x: 10, y: 20 });
const point3D = { x: 10, y: 20, z: 30 };
printPoint(point3D);
7.2 多余属性检查 #
typescript
interface User {
name: string;
age: number;
}
const user: User = {
name: 'Alice',
age: 25,
email: 'alice@example.com'
};
function createUser(user: User): void {}
createUser({
name: 'Alice',
age: 25,
email: 'alice@example.com'
});
createUser({
name: 'Alice',
age: 25,
email: 'alice@example.com'
} as User);
7.3 索引签名绕过 #
typescript
interface User {
name: string;
age: number;
[key: string]: any;
}
const user: User = {
name: 'Alice',
age: 25,
email: 'alice@example.com'
};
八、实用示例 #
8.1 配置对象 #
typescript
interface DatabaseConfig {
host: string;
port: number;
username: string;
password: string;
database: string;
ssl?: boolean;
poolSize?: number;
}
function createConnection(config: DatabaseConfig): void {
console.log(`Connecting to ${config.host}:${config.port}`);
}
8.2 API响应 #
typescript
interface ApiResponse<T> {
code: number;
message: string;
data: T;
timestamp: number;
}
interface User {
id: number;
name: string;
email: string;
}
async function fetchUser(id: number): Promise<ApiResponse<User>> {
const response = await fetch(`/api/users/${id}`);
return response.json();
}
8.3 事件处理器 #
typescript
interface EventHandler {
(event: Event): void;
}
interface EventEmitter {
on(event: string, handler: EventHandler): void;
off(event: string, handler: EventHandler): void;
emit(event: string, data?: any): void;
}
8.4 表单数据 #
typescript
interface FormData {
[key: string]: string | number | boolean | null;
}
function submitForm(data: FormData): Promise<Response> {
return fetch('/api/form', {
method: 'POST',
body: JSON.stringify(data)
});
}
九、对象类型工具 #
9.1 Pick #
typescript
interface User {
id: number;
name: string;
email: string;
age: number;
}
type UserPreview = Pick<User, 'id' | 'name'>;
const preview: UserPreview = {
id: 1,
name: 'Alice'
};
9.2 Omit #
typescript
interface User {
id: number;
name: string;
email: string;
password: string;
}
type PublicUser = Omit<User, 'password'>;
const publicUser: PublicUser = {
id: 1,
name: 'Alice',
email: 'alice@example.com'
};
9.3 Record #
typescript
type UserMap = Record<string, User>;
const users: UserMap = {
'user1': { id: 1, name: 'Alice', email: 'alice@example.com', password: '123' },
'user2': { id: 2, name: 'Bob', email: 'bob@example.com', password: '456' }
};
9.4 ReturnType #
typescript
function createUser(name: string, age: number) {
return { name, age };
}
type User = ReturnType<typeof createUser>;
const user: User = {
name: 'Alice',
age: 25
};
十、总结 #
本章介绍了TypeScript对象类型:
对象类型特性 #
- 属性类型:必需、可选、只读
- 索引签名:字符串索引、数字索引
- 方法类型:方法定义、可选方法
- 可调用类型:调用签名、构造签名
类型兼容性 #
- 结构化类型系统
- 多余属性检查
- 类型扩展和合并
最佳实践 #
- 使用接口定义对象类型
- 合理使用可选属性
- 使用只读属性保护数据
- 使用索引签名处理动态属性
- 使用工具类型简化类型定义
最后更新:2026-03-26