I use the following pattern in 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. I've defined a Thing
interface, and the relevant classes. Is there a way to achieve this sort of dynamic instantiation without resorting to a big case
statement?
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"})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.