Skip to content

2026-07-06 学习笔记

TypeScript 工具类型练习

做了 TypeScript 类型体操练习,整理了常用工具类型的用法。

常用工具类型

typescript
// Partial - 全部可选
type A = Partial<{ name: string; age: number }>

// Pick - 选取部分
type B = Pick<User, 'name' | 'email'>

// Omit - 排除部分
type C = Omit<User, 'id' | 'createdAt'>

// Record - 字典类型
type D = Record<string, number>

// ReturnType - 获取返回值类型
type E = ReturnType<typeof createUser>

实战:API 类型设计

typescript
interface Article {
  id: string
  title: string
  content: string
  tags: string[]
  createdAt: Date
}

// 创建文章:排除自动生成字段
type CreateArticle = Omit<Article, 'id' | 'createdAt'>

// 更新文章:所有字段可选
type UpdateArticle = Partial<Omit<Article, 'id'>>

// 列表项:只取展示字段
type ArticleListItem = Pick<Article, 'id' | 'title' | 'tags'>

体会

工具类型不是死记硬背,而是理解每个类型的语义

  • Partial = "可能还没填完"
  • Pick = "我只需要这几样"
  • Omit = "这些不需要你管"

类型编程的威力在于:让错误在编译时暴露,而不是运行时。

阅读量

基于 VitePress 构建