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综合练习

综合练习

为 platform 组件写严格 utility 类型。

40 分钟

综合练习

本课整合 typescript-advanced-essentials 全部主题,为 platform 组件与 API 层编写严格 utility 类型。练习贯穿 typescript-essentials 基础、nestjs-essentials 后端 DTO 模式与 nextjs-essentials 前端数据流,完成 TypeScript 路线图闭环。

学习目标

  • 设计可复用的类型工具库
  • 为 CRUD API 建模 Create/Update/List 类型
  • 在 React 组件中应用严格 props 与 async 数据类型

任务一:API 类型工具

interface Lesson {
  id: number;
  slug: string;
  title: string;
  contentMd: string;
  trackId: number;
  publishedAt: Date | null;
  createdAt: Date;
  updatedAt: Date;
}

// 实现以下类型
type CreateLessonInput = Omit<Lesson, "id" | "createdAt" | "updatedAt" | "publishedAt">;
type UpdateLessonInput = Partial<Pick<Lesson, "title" | "contentMd" | "publishedAt">>;
type LessonListItem = Pick<Lesson, "slug" | "title" | "publishedAt">;

type ApiResponse<T> =
  | { ok: true; data: T }
  | { ok: false; error: { code: string; message: string } };

type LessonResponse = ApiResponse<Lesson>;
type LessonListResponse = ApiResponse<LessonListItem[]>;

任务二:条件类型提取

type UnwrapApiResponse<T> = T extends ApiResponse<infer D> ? D : never;

type LessonData = UnwrapApiResponse<LessonResponse>; // Lesson
type LessonListData = UnwrapApiResponse<LessonListResponse>; // LessonListItem[]

function assertOk<T>(res: ApiResponse<T>): asserts res is { ok: true; data: T } {
  if (!res.ok) {
    throw new Error(res.error.message);
  }
}

任务三:React 组件 props

type LessonPageProps = {
  lesson: LessonListItem;
  contentMd: string;
  onComplete?: () => void;
};

// 从 props 派生
type LessonHeaderProps = Pick<LessonPageProps, "lesson">;

// 严格 async loader 返回类型
type LoaderResult = {
  lesson: Lesson;
  related: LessonListItem[];
};

async function loadLesson(slug: string): Promise<LoaderResult> {
  const res = await fetch(`/api/lessons/${slug}`);
  const json = (await res.json()) as ApiResponse<LoaderResult>;
  assertOk(json);
  return json.data;
}

任务四:类 + 装饰器(可选)

// 模拟 Nest 风格 validation pipe
function ValidateTarget(target: Function) {
  Reflect.defineMetadata("validated", true, target);
}

@ValidateTarget
class CreateLessonDto implements CreateLessonInput {
  constructor(
    public slug: string,
    public title: string,
    public contentMd: string,
    public trackId: number,
  ) {}
}

验收清单

  • CreateLessonInput / UpdateLessonInput / LessonListItem 派生正确
  • ApiResponse 联合类型 + assertOk 类型守卫可用
  • UnwrapApiResponse 条件类型提取 data 类型
  • 组件 props 无 any,strict 模式下零报错
  • (可选)DTO 类配合装饰器元数据

小结

综合练习 = 工具类型 + 联合收窄 + 组件/API 建模,对标真实 platform 代码结构。 恭喜完成 TypeScript 进阶 track!

加载本节练习…
← 上一课工具链