I'm attempting to instantiate classes via configuration with a utility method that looks like this.
Util.newClassByName('MyClass')
It seems that the code works as far as instantiating my class, but I get a Typescript error that I'm not sure how to resolve.
app\scripts\scraper\util.ts(18,20): error TS2322: Type 'Util' is not assignable to type 'void'.
My helper methods which is based on code I found via instantiate-a-javascript-object-using-a-string-to-define-the-class-name, is written in TypeScript.
If I put :void into the method name, I get the error that you see on line 18
class Util {
public static newClassByName(className): void {
var namespaceSegment = className.split(".");
var fn = (window || this);
for (var i = 0, len = namespaceSegment.length; i < len; i++) {
fn = fn[namespaceSegment[i]];
}
if (typeof fn !== "function") {
throw new Error("function not found");
}
return new fn(); // <-- Line 18
};
}
If I REMOVE :void from the method then I get this error on the calling code
var scraper = Util.newClassByName(config.scraper);
app\scripts\scraper\scraper-util.ts(68,23): error TS2350: Only a void function can be called with the 'new' keyword.
class Util {
public static newClassByName(className) {
var namespaceSegment = className.split(".");
var fn = (window || this);
for (var i = 0, len = namespaceSegment.length; i < len; i++) {
fn = fn[namespaceSegment[i]];
}
if (typeof fn !== "function") {
throw new Error("function not found");
}
return new fn();
};
}