TS-下篇: TS常见内置工具及类型体操

313 阅读3分钟

InstanceType

定义

TypeScript 中的一个内置类型工具,它用于获取构造函数类型实例化后的类型。

class Person {
}
type instanceType = InstanceType<typeof Person>
类型体操

获取构造函数的返回值类型也就是构造函数创建出来的实例对象的类型

type PZinstanceType<T extends new (...args: any) => any> = T extends new (...args: any[]) => infer R? R: never
应用场景

通过传入不同的类, 生产相对应的实例的工厂函数

class Person {
}
class Student {
}

function foo<T extends new (...args: any) => any>(para: T): PZinstanceType<typeof para> {
    return new para()
  }

const res = foo(Person)
const stu = foo(Student)

NonNullable

定义

TypeScript 中的一个内置类型工具,用于将可能为 nullundefined 的类型排除掉 nullundefined

type personType = number | string | (() => void) | null | undefined
type pType = NonNullable<personType>
类型体操
type PZType<T> = T extends null | undefined ? never: T
应用场景

它用于在联合类型中过滤掉null和undefined类型

type personType = number | string | (() => void) | null | undefined
type pType = NonNullable<personType>

Extract

定义-应用场景

TypeScript 中的一个内置类型工具,它用于在联合类型中提取指定类型

type personType = number | string | (() => void)
type pType = Extract<personType, number | string>
类型体操
type PZType<T, K> = T extends K? K: never

Exclude

定义-应用场景

TypeScript 中的一个内置类型工具, 它用于在联合类型中过滤掉指定类型

type personType = number | string | (() => void)
type pType = Exclude<personType, number | string>
类型体操
type PZType<T, K> = T extends K? never: T

Partial

定义-应用场景

TypeScript 中的一个内置类型工具, 它用于把对象类型中的所有属性变为可选类型

interface IPerson {
  name: string
  age: number
  id?: string
}
type personType = Partial<IPerson>
类型体操
type PZPartial<T> = {
  [K in keyof T]?: T[K]
}

Required

定义-应用场景

TypeScript 中的一个内置类型工具, 它用于把对象类型中的所有属性变为必选类型

interface IPerson {
  name: string
  age: number
  id?: string
}
type personType = Required<IPerson>
类型体操
type PZPartial<T> = {
  [K in keyof T]-?: T[K]
}

Readonly

定义-应用场景

TypeScript 中的一个内置类型工具, 它用于把对象类型中的所有属性变为只读

类型体操
type PZPartial<T> = {
  readonly [K in keyof T]: T[K]
}

Record

定义-应用场景

TypeScript 中的一个内置类型工具, 它用于定义一个键值对类型,其中键的类型要求是string | number | symbol联合类型, 使用keyof any可以获取到。参数一定义key类型, 参数二定义value类型

interface IPerson {
  name: string
  age: number
  id?: string
}
type recoreType = "JD" | "Baidu"
type personType = Record<recoreType, IPerson>
类型体操
type resType = keyof any
type PZPartial<KEYS extends resType  , V> = {
  [K in KEYS]: V
}

Pick

定义-应用场景

TypeScript 中的一个内置类型工具, 用于从某个类型中选择指定属性,并生成一个新的类型。下面例子是说从interface中取到name,age和它们的类型, 并创建一个新的类型, 类型中包含name, age属性

interface IPerson {
  name: string
  age: number
  id?: string
}
type personType = Pick<IPerson, "name" | "age">

图片.png

类型体操
type PZPartial<T, K extends keyof T> = {
  [P in K]: T[P]
}

Omit

定义-应用场景

TypeScript 中的一个内置类型工具, 用于从对象类型中过滤掉指定的key

interface IPerson {
  name: string
  age: number
  id?: string
}
type personType = Omit<IPerson, "name" | "age">
类型体操

在对象类型中全部遍历一遍key后, 直接断言。断言为若P为传入K的时候直接过滤, 取到过滤后的key

type PZPartial<T, K extends keyof T> = {
  [P in keyof T as P extends K? never: P]: T[P]
}