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
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");