TypeScript全解:泛型编程(下)

2023-06-12  本文已影响0人  littleyu

开始逐渐体操化

先来看一些内置的 TS 工具

type Person = { name: string; age: number; }

type X1 = Readonly<Person>
type X2 = Partial<Person>
type X3 = Required<Person>
type X4 = Record<string, number>
type X5 = Exclude<1 | 2 | 3, 1 | 2> // 3
type X6 = Extract<1 | 2 | 3, 2 | 4> // 2
type X7 = Omit<Person, 'name' | 'age'>

Readonly

type Readonly<T> = {
  readonly [K in keyof T]: T[K]
}

关键词 in,而不是用 :,上之前的文章种也提到过,in 多用于泛型

Partial

type Partial<T> = {
  [K in keyof T]?: T[K]
}

Required

type Required<T> = {
  [K in keyof T]-?: T[K]
}

Record

type Record<K extends string | number | symbol, V> = {
  [key in K]: V
}

Exclude

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

Extract

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

Omit

type Omit<T, K> = {
  [K2 in keyof T as (K2 extends K ? never : K2)]: T[K2]
}

Pick

type Pick<T, K extends keyof T> = {
  [K2 in keyof K]: T[K2]
}

这个时候在来实现 Omit 更加简单

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

Mutable

type Mutable<T> = {
  -readonly [K in keyof T]: T[K]
}

结论

理论上 TS 可以完成所有 JS 的功能

超牛的项目

象棋

https://github.com/chinese-chess-everywhere/type-chess

lisp 解释器

型体操天花板

https://zhuanlan.zhihu.com/p/427309936

上一篇下一篇

猜你喜欢

热点阅读