Skip to content

tools

Record

ts
type UserID = string // 定义有效的用户信息类型
type UserInfo = 'name' | 'email' | 'avatarUrl'
const users: Record<UserID, UserInfo> = {
  uid1: { name: 'user1', email: 'user1@163.com', avatarUrl: 'https://user1.com/avatar.png' },
  uid2: { name: 'user2', email: 'user1@qq.com', avatarUrl: 'https://user2.com/avatar.png' },
  uid3: { name: 'user3', email: 'user1@gmail.com', avatarUrl: 'https://user3.com/avatar.png' }
}

Partial

转为可选

ts
interface User {
  id: string
  name: string
  slug: string
  group: string
  avatarUrl: string
  about: string
}
const updateUser: Partial<User> = { about: '我是一个刚学编程的小菜鸡!' }

Required

转为必需。

ts
type User = {
  firstName: string
  lastName?: string
}

const user1: Required<User> = {
  firstName: 'John',
  lastName: 'Doe'
}

Omit

忽略指定类型。

ts
type Product = {
  X: string
  Y: string
  Z: string
}

type ProductWithoutZ = Omit<Product, 'Z'>

Pick

选取类型。

ts
type ParentType = {
  X: string
  T: number
  S: boolean
}

type ChildType = Pick<ParentType, 'X' | 'S'>