如果我有一组导入的类 classes
,我知道我可以创建一个将类的键名映射到该类的实例的类型吗?例如:
Users.ts
export default class Users {}
index.ts
// classes
export {default as Users} from './Users'
types.ts
import * as classes from './index'
type ClassInstancesMapped = {
[P in keyof typeof classes]: InstanceType<typeof classes[P]>
}
// For the example above this is equivalent to
type ClassInstances = {
Users: classes.Users;
}
(从here借来的片段)
如何修改它以包含每个类实例的通用参数?具体来说,我如何编写一个模拟这个的映射类型:
type ClassInstancesWithGeneric<T extends boolean> = {
Users: classes.Users<T>;
}
我知道上面的 (ClassInstancesWithGeneric) 工作正常,但是当我尝试修改 ClassInstancesMapped 以支持泛型时,我想不出任何工作。例如:
// Do not work
type ClassInstancesMappedGeneric<T extends boolean> = {
[P in keyof typeof classes]: InstanceType<classes[P]<T>>
}
type ClassInstancesMappedGeneric<T extends boolean> = {
[P in keyof typeof classes]: InstanceType<classes[P]><T>
}
type ClassInstancesMappedGeneric<T extends boolean> = {
[P in keyof typeof classes]: InstanceType<typeof (classes[P]<T>)>
}
type ClassInstancesMappedGeneric<T extends boolean> = {
[P in keyof typeof classes]: classes[P]<T>
}
有什么想法吗?
更新:2021 年 6 月
这看起来只能使用不受官方支持的“高级类型”来完成。相关的 Typescript Issue 进入了一些可能的实现,但即使最近有活动,它也已经超过 7 年了......