'new' expression, whose target lacks a construct signature in TypeScript
Solution 1:
David answer is great, but if you care just about quickly making it compile (for example because you are migrating from JS to TS) then you can simply put any
there to shut up complaining compiler.
TS file:
const TestConstructorFunction = function (this: any, a: any, b: any) {
this.a = a;
this.b = b;
};
let test1 = new (TestConstructorFunction as any)(1, 2);
compiles to this JS file:
var TestConstructor = function (a, b) {
this.a = a;
this.b = b;
};
var test1 = new TestConstructor(1, 2);
Just pay attention to not make this mistake:
TS file:
// wrong!
let test2 = new (TestConstructorFunction(1, 2) as any);
JS result:
// wrong!
var test2 = new (TestConstructor(1, 2));
and this is wrong. You'll get TypeError: TestConstructor(...) is not a constructor
error at runtime.
Solution 2:
Here's a simplification of the question:
const TestVectorLayer = function(layerName: string) {
};
const layer = new TestVectorLayer("");
The error is happening because TestVectorLayer
doesn't have a new signature, so layer
is implicitly typed as any
. That errors with --noImplicitAny
.
You can fix this by switching to a class, but in your case this seems a bit more complicated because the inheritance is done by the underlying framework. Because of that, you will have to do something a bit more complicated and it's not ideal:
interface TestVectorLayer {
// members of your "class" go here
}
const TestVectorLayer = function (this: TestVectorLayer, layerName: string) {
// ...
console.log(layerName);
ol.layer.Image.call(this, opts);
} as any as { new (layerName: string): TestVectorLayer; };
ol.inherits(TestVectorLayer, ol.layer.Image);
export default TestVectorLayer;
Then in the file with TestComponent
:
const layer = new TestVectorLayer(layerName); // no more compile error
Solution 3:
In my case, You have to define it as any
and has new
signature, for example.
const dummyCtx = function(txt: string) {
this.foo = txt
} as any as { new (txt: string): any }
// just use it as usual
const dctx = new dummyCtx('bar')