CodeRoadMap
首页路线题库资源库文章社区
CodeRoadMap

程序员的学习成长路线图。内容免费开放,登录后可同步路线图与课时进度。

由 程序员柏风 独立维护 · 关于作者

学习

  • 路线图
  • 课程
  • 面试题
  • 文章
  • 我

更多

  • 资源
  • 社区
  • 关于作者
  • 内容说明

© 2026 CodeRoadMap

津ICP备2026012044号-1·津公网安备12011002026155号·coderoadmap@126.com
TypeScript 进阶/课时/内置工具类型
RawBlame
课时目录12 节

TypeScript 进阶

  1. 01TS 进阶地图
  2. 02原始类型深入
  3. 03集合类型
  4. 04断言与收窄
  5. 05内置工具类型
  6. 06高级类型
  7. 07类与 OOP
  8. 08函数类型进阶
  9. 09装饰器
  10. 10命名空间
  11. 11工具链
  12. 12综合练习

内置工具类型

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());
}

练习

  • 从 platform 的 Track 类型派生 CreateTrackInput 与 TrackListItem
  • 用 ReturnType 提取某 fetch 函数的 resolved 类型
  • 用 Exclude 从联合中移除 "loading" 状态

小结

工具类型 = 类型层面的 DRY,与 REST PATCH/列表 DTO 模式天然契合。 下一课高级类型。

加载本节练习…
← 上一课断言与收窄下一课 →高级类型