- 定义帮助类型
type FilterFlags<Base, ValueType> = {
[Key in keyof Base]:
Base[Key] extends ValueType ? Key : never
}
type KeysWithValueType<Base, ValueType> =
FilterFlags<Base, ValueType>[keyof Base]
- 单纯对原始对象进行过滤
type EntriesWithValueType<Base, ValueType> =
Pick<Base, KeysWithValueType<Base, ValueType>>
- 过滤的同时进行映射
例子:将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'
})
网友评论