TypeScript工具类型 #
一、工具类型概述 #
TypeScript提供了一系列内置的工具类型,用于类型转换和操作。
二、属性修饰工具 #
2.1 Partial #
将所有属性变为可选:
typescript
interface User {
name: string;
age: number;
email: string;
}
type PartialUser = Partial<User>;
const user: PartialUser = {
name: 'Alice'
};
2.2 Required #
将所有属性变为必需:
typescript
interface User {
name: string;
age?: number;
email?: string;
}
type RequiredUser = Required<User>;
const user: RequiredUser = {
name: 'Alice',
age: 25,
email: 'alice@example.com'
};
2.3 Readonly #
将所有属性变为只读:
typescript
interface User {
name: string;
age: number;
}
type ReadonlyUser = Readonly<User>;
const user: ReadonlyUser = {
name: 'Alice',
age: 25
};
user.name = 'Bob';
三、属性选择工具 #
3.1 Pick #
选择部分属性:
typescript
interface User {
id: number;
name: string;
email: string;
password: string;
}
type UserPreview = Pick<User, 'id' | 'name'>;
const preview: UserPreview = {
id: 1,
name: 'Alice'
};
3.2 Omit #
排除部分属性:
typescript
interface User {
id: number;
name: string;
email: string;
password: string;
}
type PublicUser = Omit<User, 'password'>;
const user: PublicUser = {
id: 1,
name: 'Alice',
email: 'alice@example.com'
};
四、对象构造工具 #
4.1 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' }
};
type Status = Record<'pending' | 'approved' | 'rejected', { label: string }>;
const status: Status = {
pending: { label: 'Pending' },
approved: { label: 'Approved' },
rejected: { label: 'Rejected' }
};
五、联合类型工具 #
5.1 Exclude #
从联合类型中排除类型:
typescript
type T0 = Exclude<'a' | 'b' | 'c', 'a'>;
type T1 = Exclude<'a' | 'b' | 'c', 'a' | 'b'>;
type T2 = Exclude<string | number | (() => void), Function>;
5.2 Extract #
从联合类型中提取类型:
typescript
type T0 = Extract<'a' | 'b' | 'c', 'a' | 'f'>;
type T1 = Extract<string | number | (() => void), Function>;
5.3 NonNullable #
排除null和undefined:
typescript
type T0 = NonNullable<string | number | undefined>;
type T1 = NonNullable<string | null | undefined>;
六、函数类型工具 #
6.1 Parameters #
获取函数参数类型:
typescript
function createUser(name: string, age: number, email: string) {
return { name, age, email };
}
type UserParams = Parameters<typeof createUser>;
const params: UserParams = ['Alice', 25, 'alice@example.com'];
6.2 ConstructorParameters #
获取构造函数参数类型:
typescript
class User {
constructor(public name: string, public age: number) {}
}
type UserParams = ConstructorParameters<typeof User>;
const params: UserParams = ['Alice', 25];
6.3 ReturnType #
获取函数返回类型:
typescript
function createUser(name: string, age: number) {
return { name, age };
}
type User = ReturnType<typeof createUser>;
const user: User = {
name: 'Alice',
age: 25
};
6.4 InstanceType #
获取构造函数实例类型:
typescript
class User {
name: string;
constructor(name: string) {
this.name = name;
}
}
type UserInstance = InstanceType<typeof User>;
const user: UserInstance = new User('Alice');
七、字符串类型工具 #
7.1 Uppercase #
转换为大写:
typescript
type Upper = Uppercase<'hello'>;
7.2 Lowercase #
转换为小写:
typescript
type Lower = Lowercase<'HELLO'>;
7.3 Capitalize #
首字母大写:
typescript
type Capital = Capitalize<'hello'>;
7.4 Uncapitalize #
首字母小写:
typescript
type Uncapital = Uncapitalize<'Hello'>;
八、其他工具 #
8.1 ThisParameterType #
获取this参数类型:
typescript
function toHex(this: number) {
return this.toString(16);
}
type T = ThisParameterType<typeof toHex>;
8.2 OmitThisParameter #
移除this参数:
typescript
function toHex(this: number) {
return this.toString(16);
}
type HexFunction = OmitThisParameter<typeof toHex>;
const hex: HexFunction = toHex.bind(255);
8.3 ThisType #
标记this类型:
typescript
interface ObjectDescriptor<D, M> {
data?: D;
methods?: M & ThisType<D & M>;
}
九、实用示例 #
9.1 更新对象 #
typescript
function updateObject<T>(obj: T, updates: Partial<T>): T {
return { ...obj, ...updates };
}
interface User {
id: number;
name: string;
age: number;
}
const user: User = { id: 1, name: 'Alice', age: 25 };
const updated = updateObject(user, { age: 26 });
9.2 创建选择器 #
typescript
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
const result = {} as Pick<T, K>;
keys.forEach(key => {
result[key] = obj[key];
});
return result;
}
interface User {
id: number;
name: string;
email: string;
}
const user: User = { id: 1, name: 'Alice', email: 'alice@example.com' };
const preview = pick(user, ['id', 'name']);
9.3 创建映射 #
typescript
function createMap<T, K extends keyof T>(items: T[], key: K): Record<string, T> {
return items.reduce((map, item) => {
const keyValue = String(item[key]);
map[keyValue] = item;
return map;
}, {} as Record<string, T>);
}
十、总结 #
本章介绍了TypeScript内置工具类型:
属性修饰 #
- Partial:可选属性
- Required:必需属性
- Readonly:只读属性
属性选择 #
- Pick:选择属性
- Omit:排除属性
对象构造 #
- Record:创建对象类型
联合类型 #
- Exclude:排除类型
- Extract:提取类型
- NonNullable:排除null
函数类型 #
- Parameters:参数类型
- ReturnType:返回类型
- InstanceType:实例类型
最后更新:2026-03-26