常用类型操作

整合 TypeScript 中常用的一些类型操作方法。

1. 从数组中读取类型

const a = ['a', 'b'] as const
// b: 'a' | 'b'
const b: typeof a[number]

2. Deep Partial

TypeScript 中内置了 Partial 类型方法,但是很多时候我们需要对嵌套对象使用,此时 Partial 便不能满足我们的需求。

type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends Array<infer I>
    ? Array<DeepPartial<I>>
    : DeepPartial<T[P]>
}

// 测试
interface A {
  user: {
    age: number
    name: string
  }
}

type B = DeepPartial<A>

最后更新于