我想编写一个函数,该函数接受值是类的字典作为参数,并且在输出中我想获取包含其实例的字典
例如
classes C1, C2
function f: ({
name1: C1,
name2: C2
}): ({
name1: new C1()
name2: new C2()
})
如何为函数f编写类型以获得强类型?
答案 0 :(得分:1)
是的,您可以使用映射类型和内置条件类型InstanceType
class C1 { c1!: number}
class C2{ c2!: number }
type AllInstance<T extends Record<string, new (...a: any[]) => any>> = {
[P in keyof T]: InstanceType<T[P]>
}
function f<T extends Record<string, new () => any>>(o: T): AllInstance<T> {
const result = {} as AllInstance<T>
for(var key of Object.keys(o) as Array<keyof T>) {
result[key] = new o[key]()
}
return result;
}
let o = f({ C1,C2 })
o.C1.c1;
o.C2.c2;