Skip to content

Typescript 内置类型工具 ​

2022-11-09 16:18:25

Typescript中有很多内置的类型工具,我们分别来看一下并且看一下他们是如何实现的。

Partial ​

接收一个类型,将传入类型的属性都变为可选类型

ts
interface Person {
  name: string
  age: number
  address?: string
}

type MyPartial<T> = {
  [P in keyof T]?: T[P]
}

type ResultType = MyPartial<Person>
type ResultType2 = Partial<Person>

Readonly ​

接收一个类型,将传入类型的属性变为readonly

ts
interface Person {
  name: string
  age: number
  address?: string
}

type MyReadonly<T> = {
  readonly [P in keyof T]: T[P]
}

type ResultType = MyReadonly<Person>
type ResultType2 = Readonly<Person>

Require ​

接收一个类型,将传入类型的属性变为必选属性

ts
interface Person {
  name: string
  age: number
  address?: string
}

type MyRequired<T> = {
  [P in keyof T]-?: T[P]
}

type ResultType = MyRequired<Person>
type ResultType2 = Required<Person>

Record ​

Record<T, K>

遍历传入的类型,返回对象类型, K 为对象的key的类型,T 为对象的value的类型

ts
interface Person {
  name: string
  age: number
  address?: string
}

// 确保 K 是可以作为key的联合类型
type MyRecord<K extends keyof any, T> = {
  [P in K]: T
}

type ResultType = MyRecord<string, Person>
type ResultType2 = Record<string, Person>

Pick ​

Pick<T, K>

从 T 中选取 K 属性的类型,组成一个新的类型

ts
interface Person {
  name: string
  age: number
  address?: string
}

type MyPick<T, K extends keyof T> = {
  [P in K]: T[P]
}

type ResultType = MyPick<Person, 'name' | 'age'>
type ResultType2 = Pick<Person, 'name' | 'age'>

Omit ​

Omit<T, K>

Omit和Pick相反,从 T 中过滤 K 属性的类型,组成一个新的类型

ts
interface Person {
  name: string
  age: number
  address?: string
}

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

type ResultType = MyOmit<Person, 'name' | 'age'>
type ResultType2 = Omit<Person, 'name' | 'age'>

Exclude ​

Exclude<T, K>

传入一个联合类型T,从 T 中过滤 K 属性的类型,组成一个新的类型

ts
type Hobby = 'skiing' | 'swimming' | 'sing'

type MyExclude<T, K> = T extends K ? never : T

type ResultType = MyExclude<Hobby, 'sing'>
type ResultType2 = Exclude<Hobby, 'sing'>

Extract ​

Extract<T, K>

传入一个联合类型T,从 T 中提取 K 属性的类型,组成一个新的类型

ts
type Hobby = 'skiing' | 'swimming' | 'sing'

type MyExtract<T, K> = T extends K ? T : never

type ResultType = MyExtract<Hobby, 'sing'>
type ResultType2 = Extract<Hobby, 'sing'>

ReturnType ​

接收一个函数类型,返回函数的返回值类型

ts
type FunType = (a: string, b: string) => string

function foo() {
  return '123'
}

type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never 

type ResultType = MyReturnType<FunType>
type ResultType2 = MyReturnType<typeof foo>
type ResultType3 = ReturnType<typeof foo>

NonNullable ​

接收一个类型,从中过滤 null 和 undefined 属性的类型,组成一个新的类型

ts
type Hobby = 'skiing' | 'swimming' | 'sing' | null | undefined

type MyNonNullable<T> = T extends null | undefined ? never : T
type MyNonNullable2<T> = T & {}

type ResultType = MyNonNullable<Hobby>
type ResultType2 = MyNonNullable2<Hobby>
type ResultType3 = NonNullable<Hobby>

Released under the MIT License.