I have been looking into creating classes from strings in Javascript, until I came across this:
var instance = new window[classString]();
However, this does not seem to work in Typescript, since there is type information missing.
Details:
interface SomeInterface{
structuredData: any;
}
class A implements SomeInterface {
}
I am storing JSON serialized class information in a database. Let's say I have a model class A, that class's properties are serialized as JSON string in the frontend and sent to the database along with the class name that represents this data, i.e. the database contains a class_type column that contains the name of the class. In this case that would be the string 'A'. Now, I would like to get that data back into my application and dynamically construct an instance from that data.
If we look at the Javascript instantiation code I found above, I would love to do something like this:
let instance = new window['A']();
instance.structuredData = foo;
Since those classes contain generic parameters that adhere to a certain interface I would be able to assign the serialized data to those newly instantiated instances.
I'm using Angular2/Webpack and would really appreciate any hints as to how to do this.
When using the code like I mentioned above, I get the following compiler error:
Cannot use 'new' with an expression whose type lacks a call or construct signature.
If I try to circumvent the strict type checking by using
declare var window;
I get the following error:
window['classString'] is not a constructor
let instance = new window['A']();in a standalone .ts file, it compiles fine.