写工具库常用的ts类型体操最佳实践

298 阅读1分钟

简介

  • 写工具库经常遇到配置相关的ts规范
  • 不想了解类型体操 直接获取最佳实践

实例

一个工具库的初始化写法

// 默认选项
const defaults: DefaultOptions = {
  a: true,
}

// 选项映射列表
const optionsMap: ApiMap = {
  a: afunc,
  b: bfunc,
}

export function config(options: Options) {
  // 内部选项
  const innerOptions: InnerOptions = { ...defaults, ...options }

  // 初始化选项
  for (const key in innerOptions) {
    optionsMap[key](innerOptions[key])
  }
}

function afunc(val: boolean) {

}

function bfunc(val: number) {

}

最佳实践的通用类型

map

type MyApiMap<Type extends { [key: string]: any }> = {
  [Key in keyof Type]-?: (params: Exclude<Type[Key], undefined>) => any
}

合并

/**
 * 合并两个 interface
 * 冲突第二个覆盖第一个
 */
type Merge<
  Type1 extends { [Key: string]: any },
  Type2 extends { [Key: string]: any },
> = {
  [Key in keyof (Type1 & Type2)]: Key extends keyof Type2
    ? Type2[Key]
    : Key extends keyof Type1
    ? Type1[Key]
    : never
}

Exclude

/**
 * 从 type1 中剔除掉 type2 的类型
 */
type MyExclude<Type1, Type2> = Type1 extends Type2 ? never : Type1

需要手写的类型

外部的 Options

export interface Options {
  a?: boolean
  b?: number
}

默认的 DefaultOptions

export interface DefaultOptions {
  b: boolean
}

剩余的

export type InnerOptions = Merge<Options, DefaultOptions>

export type ApiMap = MyApiMap<InnerOptions>