TypeScript学习笔记 -- 一些常见和常用的内置类型工具

本文详细介绍了 TypeScript 中的几个关键类型工具,包括 Exclude 用于从联合类型中排除指定类型,Extract 获取联合类型中的交集,Record 用于创建对象结构类型,Readonly 将类型的所有属性设置为只读,Required 将对象类型的所有属性设为必需,而 Partial 则将所有属性设为可选。这些工具在类型系统的灵活性和精确性方面发挥着重要作用。
Exclude<UnionType, ExcludedMembers>

从 UnionType 中剔除既在UnionType又在ExcludedMembers中的类型

type A = 'a' | 'b' | 'c'
type B = 'b'
type C = Exclude<A, B> // 'a' | 'c'
Extract<Type, Union>

它的作用与 Exclude 正好相反,是找出两个类型的交集部分

type A = 'a' | 'b' | 'c'
type B = 'b'
type C = Extract<A, B> // 'b'
Record<Keys, Type>

生成一个对象结构的类型,其中 Keys 为属性且Keys也是有类型限制的,只能接收 string | number | symbol 中的类型, Type 为属性对应的类型,如果 Type 是值类型,则为属性对应的值

type A = 'a' | 'b' | 'c'
type B = 'example' | number
interface O {
  age: number
  name: string
}

type R1 = Record<A, O> // {a: O; b: O; c: O}
// 试一下反着来
type R2 =  Record<O, A> // 会出现下面的报错信息:
// Type 'O' does not satisfy the constraint 'string | number | symbol'.
// Type 'O' is not assignable to type 'symbol'.

// 试一下第二个参数为 B
type R3 = Record<A, B> // {a: B; b: B; c: B}

// 然后继续调换参数的位置
type R4 = Record<B, A> // type C = { [x: number]: A; example: A; }
Readonly<Type>

在这个内置类型工具中,Type 必须是有 property 的类型,如果是传入的 number | string 之类的,且声明的关键字非 const,则仍然可以修改值,常见的 Type 一般是接口、type 定义的结构化的类型(通常是对象字面量形式), 以及数组之类的

const arr: Readonly<number[]> = [1, 2, 3]
arr.push(4) // Error: Property 'push' does not exist on type 'readonly number[]'

interface O {
  name: string
}

const obj: Readonly<O> = {
  name: 'example'
}

obj.name = 'test' // Error: Cannot assign to 'name' because it is a read-only property.
Required<Type>

Type 一般来说需要一个对象类型或者接口,Required<Type>会将传入的Type中的所有属性都变成必须的

interface Obj {
  name: string
  desc?: string
}

const o: Required<Obj> = {
  name: 'example'
}
// 编辑器会在 o 下面显示一个红色小波浪线,报错信息如下
// Property 'desc' is missing in type '{ name: string; }' but required in
// type 'Required<Obj>'.

// 使用接口定义的时候,desc 属性是可选的,但通过 Required 这个内置的类型工具将
// 其转换为必填的,如果需要一个结构和属性与已定义的接口一致但需要保持所有属性都是
// 必要的,使用 Required 会十分方便

Partial<Type>

与上面的 Required 相反,Partial 的作用则是将所有属性都变为可选的。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值