美文网首页
Typescript过滤和映射object类型

Typescript过滤和映射object类型

作者: rainmanhhh | 来源:发表于2020-02-25 10:52 被阅读0次
  1. 定义帮助类型
type FilterFlags<Base, ValueType> = {
  [Key in keyof Base]:
  Base[Key] extends ValueType ? Key : never
}
type KeysWithValueType<Base, ValueType> =
  FilterFlags<Base, ValueType>[keyof Base]
  1. 单纯对原始对象进行过滤
type EntriesWithValueType<Base, ValueType> = 
  Pick<Base, KeysWithValueType<Base, ValueType>>
  1. 过滤的同时进行映射
    例子:将openapi生成器默认生成的api class表映射为api实例表
function createApiInstances<Conf, Base extends new (conf: Conf) => any, A extends {
  [k: string]: any
}>(
  apis: A, base: Base, conf: Conf
) {
  const result = {} as any
  for (const k in apis) {
    if (apis.hasOwnProperty(k)) {
      const item = (apis as any)[k]
      if (base.isPrototypeOf(item)) {
        result[k] = new item(conf)
      }
    }
  }
  type Mapped = {
    [k in keyof A]: InstanceType<A[k]>
  }
  return result as Pick<Mapped, KeysWithValueType<A, Base>>
}

export const apis = createApiInstances(apiClasses, BaseAPI, new Configuration({
  basePath: 'http://localhost:8080'
})

相关文章

网友评论

      本文标题:Typescript过滤和映射object类型

      本文链接:https://www.haomeiwen.com/subject/xpezqhtx.html