javascript - 'new' 表达式,其目标在 TypeScript 中缺少构造签名

标签 javascript typescript

我们有以下 TestComponent.ts TypeScript 类:

01: import TestVectorLayer from './TestVectorLayer'
02: 
03: export class TestComponent implements OnInit {
04:   private foo: any;
05: 
06:   constructor() { }
07: 
08:   const layer = new TestVectorLayer("foo");
09: }

以及以下 TestVectorLayer.ts 函数:

请记住,OpenLayer 的 3 使用 Google Closure Library,这就是 TestVectorLayer 不是 TypeScript 类的原因。

01: declare let ol: any;
02:
03: const TestVectorLayer = function (layerName: string) {
04:   ...
05:   console.log(layerName);
06:
07:   ol.layer.Image.call(this, opts);
08: }
09:
10: ol.inherits(TestVectorLayer as any, ol.layer.Image as any);
11:
12: export default TestVectorLayer; 

我们收到以下错误:

Error on Line 08 in TestComponent.ts class:

[ts] 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type. import TestVectorLayer

TypeScript 的 package.json 版本:

开发依赖:

"typescript": "~2.2.1"

最佳答案

David 的回答很好,但是如果您只想快速编译它(例如,因为您正在从 JS 迁移到 TS),那么您可以简单地将 any 放在那里以关闭提示的编译器。

TS 文件:

const TestConstructorFunction = function (this: any, a: any, b: any) {
    this.a = a;
    this.b = b;
};

let test1 = new (TestConstructorFunction as any)(1, 2);

编译成这个 JS 文件:

var TestConstructor = function (a, b) {
    this.a = a;
    this.b = b;
};
var test1 = new TestConstructor(1, 2);

注意不要犯这个错误:

TS 文件:

// wrong!
let test2 = new (TestConstructorFunction(1, 2) as any);

JS 结果:

// wrong!
var test2 = new (TestConstructor(1, 2));

这是错误的。你会在运行时得到 TypeError: TestConstructor(...) is not a constructor 错误。

关于javascript - 'new' 表达式,其目标在 TypeScript 中缺少构造签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43623461/

相关文章:

javascript - 在加载到主页的部分页面中使用 Angular

javascript - Ionic 3 中的 CORS hell

angular - 从订阅 typescript 返回值

Angular Material 如何从 mat-table 设置 mat-sort-header

typescript - 仅当接收函数也返回 promise 时,如何将返回类型键入为 promise ?

javascript - 当固定div位置与父div重叠时如何将其更改为绝对位置

javascript - 如何使用 jQuery 检测点击事件是否发生?

javascript - 如何监视原生 JavaScript 函数?比如.find()?

javascript - 屏幕调整大小后谷歌地图显示?

javascript - ng2-bootstrap,从父组件调用子组件中定义的Modal