简介
- 写工具库经常遇到配置相关的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
}
合并
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
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>