Z
ZHANK
高级类型

内置工具类型

掌握 Partial、Required、Pick、Omit、Record 等

内置工具类型

TypeScript 内置了大量工具类型,让你轻松变换已有类型。

学完本章你将: 掌握 Partial、Required、Pick、Omit、Record 等。


属性修饰工具

typescript
interface User {
    name: string;
    age: number;
    email: string;
}

// Partial —— 全部变为可选
type PartialUser = Partial<User>;
// { name?: string; age?: number; email?: string }

// Required —— 全部变为必填
type RequiredUser = Required<PartialUser>;
// { name: string; age: number; email: string }

// Readonly —— 全部变为只读
type ReadonlyUser = Readonly<User>;

// 实战
function updateUser(id: string, changes: Partial<User>): void {
    // changes 可以只传部分字段
}

选取工具

typescript
// Pick —— 选取指定属性
type UserPreview = Pick<User, "name" | "email">;
// { name: string; email: string }

// Omit —— 排除指定属性
type UserWithoutEmail = Omit<User, "email">;
// { name: string; age: number }

Record 与 Exclude/Extract

typescript
// Record —— 构造对象类型
type PageInfo = Record<string, { title: string; url: string }>;

const pages: PageInfo = {
    home: { title: "首页", url: "/" },
    about: { title: "关于", url: "/about" },
};

// Exclude —— 从联合类型排除
type T = Exclude<"a" | "b" | "c", "a">; // "b" | "c"

// Extract —— 从联合类型提取
type E = Extract<"a" | "b" | "c", "a" | "c">; // "a" | "c"

函数工具

typescript
// Parameters —— 获取函数参数类型
function createUser(name: string, age: number): User {
    return { name, age, email: "" };
}
type Params = Parameters<typeof createUser>; // [string, number]

// ReturnType —— 获取函数返回值类型
type Result = ReturnType<typeof createUser>; // User

// NonNullable —— 移除 null/undefined
type NN = NonNullable<string | null | undefined>; // string