[英]Is an array of types possible in Typescript?
I use the following pattern in Javascript: 我在Javascript中使用以下模式:
var things = {
"blue": BlueThing,
"heavy": HeavyThing,
"imaginary": ImaginaryThing
};
var my_thing = things[thing_type]();
I'm migrating the codebase to Typescript, and I can't find a way to achieve the same thing. 我正在将代码库迁移到Typescript,但找不到找到相同方法的方法。 I've defined a
Thing
interface, and the relevant classes. 我已经定义了
Thing
接口和相关的类。 Is there a way to achieve this sort of dynamic instantiation without resorting to a big case
statement? 有没有一种方法可以实现这种动态实例化而无需诉诸大
case
语句?
OK, I sorted this out. 好,我整理了一下。
Using the constructor interface pattern, I now have this: 使用构造函数接口模式,我现在有以下内容:
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.