'new' expression, whose target lacks a construct signature in TypeScript

后端 未结 2 584
闹比i
闹比i 2020-12-14 00:39

We have the following TestComponent.ts TypeScript class:

01: import TestVectorLayer from \'./TestVectorLayer\'
02: 
03: export class TestCompone         


        
2条回答
  •  被撕碎了的回忆
    2020-12-14 01:11

    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
    

提交回复
热议问题