我们有以下TestComponent.ts种类型的脚本:

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闭包库,这就是为什么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"表达式的目标缺少构造签名,它隐式地具有"any"类型.

TypeScript的package.json个版本:

依赖性:

"typescript": "~2.2.1"

推荐答案

以下是问题的简化:

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

const layer = new TestVectorLayer("");

发生错误是因为TestVectorLayer没有新签名,所以layer隐式键入为any.这是--noImplicitAny的错误.

您可以通过切换到类来解决这个问题,但在您的情况下,这似乎有点复杂,因为继承是由底层框架完成的.因此,你将不得不做一些更复杂的事情,这并不理想:

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

Typescript相关问答推荐

如何将@for的结果绑定到变量?

定义JMX的类型:类型上不存在属性键

如何防止TypeScript允许重新分配NTFS?

与字符串文字模板的结果类型匹配的打字脚本

打字脚本中泛型和直接类型重新映射的不同行为

来自类型脚本中可选对象的关联联合类型

带switch 的函数的返回类型的类型缩小

Angular NgModel不更新Typescript

Angular 15使用react 式表单在数组内部创建动态表单数组

TypeScrip:来自先前参数的参数中的计算(computed)属性名称

布局组件中的Angular 17命名路由出口

声明文件中的类型继承

如何缩小函数的返回类型?

在Cypress中,是否可以在不标识错误的情况下对元素调用.Click()方法?

创建依赖函数参数的类型

缩小对象具有某一类型的任意字段的范围

为什么发送空字段?

递归类型别名的Typescript 使用

递归JSON类型脚本不接受 node 值中的变量

断言同级为true或抛出错误的Typescript函数