我们有以下 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/