TypeScript 工具类型 — Utility Types

TypeScript 附带了大量类型,可以帮助进行一些常见的类型操作,通常称为 Utility Types

本章介绍了最流行的工具类型。

Partial

Partial 将对象中的所有属性更改为可选。

interface Point {
  x: number
  y: number
}

let pointPart: Partial<Point> = {} // Partial 允许 x 和 y 是可选的
pointPart.x = 10

Required

Required 更改对象中需要的所有属性。与 Partial 相反。

interface User {
  name?: string
  age?: number
}

const user: User = { name: 'O.O' }

const user2: Required<User> = { name: 'O.O' }
// 类型 "{ name: string; }" 中缺少属性 "age",但类型 "Required<User>" 中需要该属性。ts(2741)

Record

Record 是定义具有特定键类型和值类型的对象类型的快捷方式。

const nameAgeMap: Record<string, number> = {
  KAI: 27,
  LAY: 30
}

Record<string, number> 相当于 { [key: string]: number }

Omit

Omit 从对象类型中删除键。

interface Person {
  name: string
  age: number
  location?: string
}

const user: Omit<Person, 'age' | 'location'> = {
  name: 'D.O' // Omit 从类型中删除了 age 和 location,不能在此处定义
}

Pick

Pick 从对象类型中删除除指定键以外的所有键。与 Omit 相反。

interface Person {
  name: string
  age: number
  location?: string
}

const user: Pick<Person, 'name'> = {
  name: 'O.O' // Pick 只保留了 name,因此 age 和 location 已从类型中删除,无法在此处定义
}

Exclude

Exclude 从联合中删除类型。

type Primitive = string | number | boolean

const value: Exclude<Primitive, string> = true // 此处不能使用字符串,因为 Exclude 将其从类型中删除。

ReturnType

ReturnType 提取函数类型的返回类型。

type foo = () => {
  x: number
  y: number
}

const point: ReturnType<foo> = {
  x: 10,
  y: 20
}

Parameters

Parameters 将函数类型的参数类型提取为数组。

type PointPrinter = (p: { x: number; y: number }) => void
const point: Parameters<PointPrinter>[0] = {
  x: 10,
  y: 20
}

更多资料

更多工具类型的详细内容可查阅 TS 官网的 Utility Types 章节

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值