[英]Is an array of types possible in Typescript?
我在Javascript中使用以下模式:
var things = {
"blue": BlueThing,
"heavy": HeavyThing,
"imaginary": ImaginaryThing
};
var my_thing = things[thing_type]();
我正在将代码库迁移到Typescript,但找不到找到相同方法的方法。 我已经定义了Thing
接口和相关的类。 有没有一种方法可以实现这种动态实例化而无需诉诸大case
语句?
好,我整理了一下。
使用构造函数接口模式,我现在有以下内容:
interface ThingConstructor {
new (options: {[key: string]: string}) : Thing
}
interface Thing{
/* * */
}
function thingFactory(type: ThingConstructor) : Function{
return function(options) : Thing {
return new type(options)
}
}
--------
things: {[key: string]: Function}
--------
things["blue"] = thingFactory(BlueThing)
var my_thing = things[thing_type]({"stripes": "vertical"})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.