【发布时间】:2021-04-20 22:12:50
【问题描述】:
我正在尝试将映射类型与打字稿一起使用,这应该是可能的,但遇到了一些问题。
假设我有 3 个班级:
class A {
public foo1 = 1;
}
class B {
public foo2 = 1;
}
class C {
public foo3 = 1;
}
const base = [A, B, C] as const;
基本上,我想要的是将base 传递给某个函数,并返回一个包含 3 个匹配实例的数组。
type CTOR = new(...args: any[]) => any
function instantiate1<T extends ReadonlyArray<CTOR>>(arr: T): {[K in keyof T]: T[K]} {
const items = arr.map(ctor => new ctor());
return items as any; //Don't mind about breaking type safety inside the function
}
现在返回:
const result1 = instantiate2(base) //type is [typeof A, typeof B, typeof C]
这是有道理的,因为我还没有真正“映射”类型,只是确保语法有效。
但是,如果我尝试实际映射类型:
function instantiate2<T extends ReadonlyArray<CTOR>>(arr: T): {[K in keyof T]: InstanceType<T[K]>} {
const items = arr.map(ctor => new ctor());
return items as any; //Don't mind about breaking type safety inside the function
}
我收到T[K] 不满足实例类型约束的错误。
任何人都可以作为解决方法的想法?
【问题讨论】:
标签: typescript