'new'表达式,其目标在TypeScript中缺少构造签名 [英] 'new' expression, whose target lacks a construct signature in TypeScript

查看:3695
本文介绍了'new'表达式,其目标在TypeScript中缺少构造签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有以下 TestComponent.ts TypeScript类:

We have the following TestComponent.ts TypeScript class:

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库,这就是为什么 TestVectorLayer 不是TypeScript类。

Keep in mind that OpenLayer's 3 is using the Google Closure Library, that's why TestVectorLayer is not a TypeScript class.

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'表达式,其目标缺少构造签名,隐式具有any类型。
import TestVectorLayer

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

TypeScript的 package.json 版本:

The package.json versions of TypeScript:

devDependencies:

devDependencies:

"typescript": "~2.2.1"


推荐答案

以下是问题的简化:

const TestVectorLayer = function(layerName: string) {
};

const layer = new TestVectorLayer("");

发生错误是因为 TestVectorLayer 没有' t有一个新签名,因此 layer 隐式输入为 any 。错误 - noImplicitAny

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; 

然后在包含 TestComponent 的文件中:

const layer = new TestVectorLayer(layerName); // no more compile error

这篇关于'new'表达式,其目标在TypeScript中缺少构造签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆