Reputation: 4044
In TypeScript, I saw in other discussions that there should be a way to create a class whose type depends on a variable.
For instance, if we have . . .
class MyClass {
someFunc(){alert("Hello");}
}
var myClassName = "MyClass";
The answers supposedly were either:
Answer #1:
var myClassInstance = new (<any>window)[myClassName]();
Answer #2:
var myClassInstance = Object.create(window[myClassName]);
I'm trying these in my console, but neither works for me.
For #1, I get error messages: "Syntax Error," or if I omit <any>
then "Object doesn't support this action".
For #2, I get error messages: "Object.create: argument is not an Object and is not null"
Does anyone have any ideas why these aren't working for me, and/or how I can instantiate a class in Typescript based on the value of a variable that holds the class name? Thank you!
Upvotes: 2
Views: 929
Reputation: 1
The reason those "answers" don't work is because MyClass
is not a property of the global object (window in your case)
This is true with variables declared in the global scope using let
and const
as well
However, since you seem to be willing to switch to old school definition, i.e. willing to rewrite the class definitions, you can always use this instead - with the bonus that there is minimal rewrite involved
var
not let
or const
var MyClass = class MyClass {
someFunc(){alert("Hello");}
}
var AnotherClass = class AnotherClass {
someFunc(){alert("Hello again");}
}
var YetAnotherClass = class YetAnotherClass {
someFunc(){alert("Hello once more");}
}
Then you can simply
let instance = new window[myClassName]();
Also, depending on where/how the classes are defined (in an import?), it may actually be required to do something like
window.MyClass = class MyClass {
someFunc(){alert("Hello");}
}
instead
Upvotes: 1
Reputation: 44105
You can't do it with class
- you'd have to use an ES5 constructor:
function MyClass() {}
MyClass.prototype.someFunc = function() {
alert("Hello!");
};
var myClassName = "MyClass";
var myClassInstance = new window[myClassName]();
myClassInstance.someFunc();
Upvotes: 3