0

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?

3
  • Object.keys(things)?? just a guess Commented Apr 18, 2017 at 16:17
  • @TomMillard The point is I can't create a things dictionary in TypeScript since types have no type. Commented Apr 18, 2017 at 16:18
  • Typescript is a superset of JavaScript, and all valid Javascript is also valid Typescript. Therefore, it's not really clear what issue you are having, or why this code doesn't work as is. Commented Apr 18, 2017 at 16:18

1 Answer 1

0

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"})
Sign up to request clarification or add additional context in comments.

1 Comment

Maybe specify the function type too? (options) => Thing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.