TypeScript 高级类型体操指南

2025 年 4 月 18 日

354 字

2 分钟

技术笔记

TypeScript 高级类型体操指南

TypeScript 的类型系统是图灵完备的,这意味着你可以用类型来实现各种复杂的逻辑。本文将带你从入门到进阶。

条件类型

type IsString<T> = T extends string ? true : false

type A = IsString<string>  // true
type B = IsString<number>  // false

映射类型

type Readonly<T> = {
  readonly [P in keyof T]: T[P]
}

type Optional<T> = {
  [P in keyof T]?: T[P]
}

模板字面量类型

type EventName = `on${Capitalize<string>}`
// "onClick" | "onHover" | ...

type CSSProperty = `${string}-${string}`
// "margin-top" | "font-size" | ...

递归类型

type DeepReadonly<T> = {
  readonly [P in keyof T]: T[P] extends object
    ? DeepReadonly<T[P]>
    : T[P]
}

实战:实现 DeepPartial

type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends object
    ? DeepPartial<T[P]>
    : T[P]
}

interface User {
  name: string
  profile: {
    age: number
    address: {
      city: string
    }
  }
}

type PartialUser = DeepPartial<User>
// 所有属性都变为可选,包括嵌套的

实战:实现路径类型

type PathKeys<T> = T extends object
  ? {
      [K in keyof T & string]: K | `${K}.${PathKeys<T[K]>}`
    }[keyof T & string]
  : never

type UserPaths = PathKeys<User>
// "name" | "profile" | "profile.age" | "profile.address" | "profile.address.city"

类型体操练习网站

推荐 Type Challenges,从 Easy 到 Hard 循序渐进。

总结

TypeScript 的类型系统非常强大,掌握高级类型可以让你写出更安全、更优雅的代码。但也要注意适度,不要为了炫技而过度使用复杂类型。

TypeScript 高级类型体操指南
https://momo-blog.pages.dev/blog/typescript-advanced-types
作者
栗辉
发布时间
2025 年 4 月 18 日
许可协议
CC BY-NC-SA 4.0
?

正在加载评论...

输入关键词开始搜索