内置工具类型
Partial、Pick、Omit、Record、Exclude、keyof 等。
35 分钟
内置工具类型
TypeScript 标准库提供大量 Utility Types,从已有类型派生新类型而无需重复字段。本课在 typescript-essentials 入门基础上系统讲解 Partial、Required、Pick、Omit、Record、Exclude、Extract、NonNullable、ReturnType、Parameters、Awaited 等,并展示在 nestjs-essentials DTO 与 nextjs-essentials 组件 props 中的典型用法。
学习目标
- 熟练使用 Pick/Omit/Partial/Required 组合
- 用 Exclude/Extract 操作联合类型
- 从函数签名提取 ReturnType 与 Parameters
对象变换
interface Lesson {
id: number;
slug: string;
title: string;
contentMd: string;
publishedAt: Date | null;
}
type LessonCreate = Omit<Lesson, "id" | "publishedAt">;
type LessonUpdate = Partial<Pick<Lesson, "title" | "contentMd">>;
type LessonSummary = Pick<Lesson, "slug" | "title">;
type LessonEntity = Required<Pick<Lesson, "id" | "slug">>;
Record 与 Readonly
type TrackLevel = "beginner" | "intermediate" | "advanced";
type LevelLabels = Record<TrackLevel, string>;
const labels: LevelLabels = {
beginner: "入门",
intermediate: "进阶",
advanced: "高级",
};
type FrozenConfig = Readonly<{ apiBase: string; timeout: number }>;
联合操作
type Status = "draft" | "published" | "archived";
type ActiveStatus = Exclude<Status, "archived">; // "draft" | "published"
type StringOrNumber = string | number | boolean;
type OnlyString = Extract<StringOrNumber, string>; // string
type MaybeId = number | null | undefined;
type DefiniteId = NonNullable<MaybeId>; // number
函数相关
async function fetchLesson(slug: string): Promise<Lesson> {
const res = await fetch(`/api/lessons/${slug}`);
return res.json();
}
type FetchLessonParams = Parameters<typeof fetchLesson>; // [slug: string]
type FetchLessonResult = ReturnType<typeof fetchLesson>; // Promise<Lesson>
type LessonData = Awaited<ReturnType<typeof fetchLesson>>; // Lesson
组合实战
type CreateLessonInput = Omit<Lesson, "id" | "publishedAt">;
type PatchLessonInput = Partial<Pick<Lesson, "title" | "contentMd" | "publishedAt">>;
function updateLesson(id: number, patch: PatchLessonInput): Promise<Lesson> {
return fetch(`/api/lessons/${id}`, {
method: "PATCH",
body: JSON.stringify(patch),
}).then((r) => r.json());
}