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

原始类型深入

boolean、number、string、void、null、undefined、unknown、any、never。

30 分钟

原始类型深入

typescript-essentials 已介绍 string、number 等基础类型;本课系统梳理 boolean、number、string、void、null、undefined、unknown、any、never 的语义边界与最佳实践。正确选用原始类型是 nestjs-essentials DTO 校验与 nextjs-essentials 组件 props 类型安全的基础。

学习目标

  • 区分 any、unknown、never 的使用场景
  • 理解 void vs undefined 在函数签名中的差异
  • 在 strict 模式下正确处理 null 与 undefined

类型安全光谱

// any:放弃检查,仅用于迁移遗留代码
function legacyParse(input: any): any {
  return JSON.parse(input);
}

// unknown:安全的外部输入容器,使用前必须收窄
function safeParse(input: unknown): unknown {
  if (typeof input !== "string") {
    throw new Error("expected string");
  }
  return JSON.parse(input);
}

// never:不可能的值,用于穷尽检查
function assertNever(x: never): never {
  throw new Error(`unexpected: ${x}`);
}

void 与 undefined

// 回调:不关心返回值时用 void(允许 return undefined)
type EventHandler = () => void;

const handler: EventHandler = () => {
  return undefined; // OK:void 兼容 undefined
};

// 显式返回 undefined 的 API
function getConfig(): undefined | { apiBase: string } {
  return undefined;
}

null 与 strictNullChecks

interface User {
  id: number;
  nickname: string | null; // 明确「可能为空」
}

function displayName(user: User): string {
  return user.nickname ?? `User#${user.id}`;
}

// 错误示范:把 null 与 undefined 混为一谈
// const name: string = user.nickname; // strict 下报错

never 在联合类型中

type Shape = { kind: "circle"; radius: number } | { kind: "square"; side: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
    default:
      return assertNever(shape);
  }
}

练习

  • 将项目中 3 处 any 改为 unknown 并添加类型守卫
  • 写一个返回 的 并在 switch 中使用
never
assertNever
  • 对照 tsconfig 中 strictNullChecks 理解 nullable 字段设计
  • 小结

    any 是逃生舱,unknown 是安全默认,never 是穷尽保障。 下一课集合类型。

    加载本节练习…
    ← 上一课TS 进阶地图下一课 →集合类型