是否可以将以下代码转换为使用Typescript?
public shops: string[] = [
"AShop",
"BShop",
"CShop",
];
this.shops.forEach((shop, index) => {
let instance = new window[shop](index);
this.instances.push(instance);
});
以下方法不适用于Typescript
,因为范围内不存在window
。我无法编译它。 (虽然它适用于香草JS)
有没有办法将循环中的变量名shop
视为表达式并基于它创建动态类?
答案 0 :(得分:1)
试试这个:
const shops: string[] = ["AShop", "BShop", "CShop"];
class BaseShop {
public constructor(index: number) {
console.log(index);
}
}
class AShop extends BaseShop { }
class BShop extends BaseShop { }
class CShop extends BaseShop { }
interface ShopContructor {
new (index: number): BaseShop;
}
interface Window {
AShop: ShopContructor;
BShop: ShopContructor;
CShop: ShopContructor;
[shop: string]: ShopContructor;
}
window.AShop = AShop;
window.BShop = BShop;
window.CShop = CShop;
const instances: BaseShop[] = [];
shops.forEach((shop: string, index: number) => {
let instance = new window[shop](index);
instances.push(instance);
});
console.log(instances);
答案 1 :(得分:0)
这是一个奇怪的结构,因为如果在全局范围内有动态类,则在编译时无法对其进行良好的类型检查。我建议在这里使用<any>
并将其完成。如果您希望生成的实例具有某些类型保证,则应使用变量类型或强制转换显式指定它们:
this.shops.forEach((shop, index) => {
let instance = new (<any>window)[shop](index);
this.instances.push(instance);
});