3

I'm using typescript, and I want to map a string to a type so I can make instances of certain type based on a string I have.

I'm writing to node.js

For example - I get from a DB the value "range" and for that case I want to use my class "RangeFilter", but in the case of the value "size" I want to use the class "SizeFilter". They all inherit from the interface "IFilter".

So is there a way to map (create a dictionary) between the values to the type

So it could be like this

map: {key: string, value: IFilter};

Return new map["range"] //returns RangeFilter

5

1 Answer 1

4

There is a way.
Basically all you need to know is that the type of a class MyClass is: { new(): MyClass }.

Then you can do:

interface IFilter {}

type FilterConstructor = { new(): IFilter };

class RangeFilter implements IFilter {}

class SizeFilter implements IFilter {}

let ctors: { [key: string]: FilterConstructor } = {};
ctors["range"] = RangeFilter;
ctors["size"] = SizeFilter;

function factory<T extends IFilter>(key: string): T {
    let ctor = ctors[key];

    return ctor == null ? null : new ctor() as T;
}

let rangeFilter: RangeFilter = factory("range");

(code in playground)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you ! Helped a lot

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.