Typescript 返回此值的命名空间中函数的类型定义
我尝试在返回this的命名空间(Typescript 返回此值的命名空间中函数的类型定义,typescript,Typescript,我尝试在返回this的命名空间(L.DomEvent.on(e))中为函数编写类型定义。JavaScript源代码如下 L.DomEvent = { // @function on(el: HTMLElement, eventMap: Object, context?: Object): this on: function(e) { // do stuff return this; } } 看 我首先写下如下定义 declare name
L.DomEvent.on(e)
)中为函数编写类型定义。JavaScript源代码如下
L.DomEvent = {
// @function on(el: HTMLElement, eventMap: Object, context?: Object): this
on: function(e) {
// do stuff
return this;
}
}
看
我首先写下如下定义
declare namespace L {
export namespace DomEvent {
export function on(el: HTMLScriptElement): this;
}
}
但是编译器会在消息中抛出一个错误
error TS2526: A 'this' type is available only in a non-static member of a class or interface.
虽然我可以将输出从
this
更改为any
(它可以工作),但我想知道是否有更好的解决方案来定义输出。基于github中的代码,您的声明应该如下所示:
declare namespace L {
export namespace DomEvent {
export function on(el: HTMLElement, types: string, fn: Function, context?: any): typeof DomEvent;
}
}
()
只有在需要时才将this
作为类型返回,但在本例中,返回的this
是DomEvent
名称空间,因此我们返回typeof DomEvent