如何定义自定义传单控件的类型

Boh*_*Hew 11 leaflet typescript

查看类型定义时,@types/leaflet您会看到定义的自定义控件,类似于:

export namespace Control {
    ...
    class Zoom extends Control {
        constructor(options?: ZoomOptions);
        options: ZoomOptions;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

但是,通过以下方式创建自定义控件时:

declare module 'leaflet' {
    namespace Control {
        class CustomControl extends Control {
            constructor(options: CustomOptions);
        }
    }
    namespace control {
        function customControl(options: CustomOptions): Control.CustomControl;
    }
}

L.Control.CustomControl = L.Control.extend({
    ...
});
Run Code Online (Sandbox Code Playgroud)

引发打字错误: Type '(new (...args: any[]) => any) & typeof Class' is missing the following properties from type 'typeof CustomControl': Zoom, Attribution, Layers, Scale, and 6 more.

这似乎是由于名称空间和类Control通过Typescript的声明合并而发生的。这导致CustomControl需要名称空间中的属性,而不仅仅是类。

有没有一种方法可以解决此问题或在不强制类型的情况下规避它any

Nai*_*nov 3

我们需要为方法“extend”添加更多类型。

在控件声明之前插入此代码

declare module 'leaflet' {
  namespace Control {
    function extend(props: any): {new(...args: any[]): any} & typeof Control;
  }
}
Run Code Online (Sandbox Code Playgroud)

与会员

declare module 'leaflet' {
  namespace Control {

    function extend<T extends Object>(props: T): {new(...args: any[]): T} & typeof Control;
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以为 Handler 添加相同的声明