Haoliang Yu Haoliang Yu - 1 month ago 8
TypeScript Question

Type definition for function in a namespace that returns this

I try to write the type definition for a function in a namespace (

L.DomEvent.on(e)
) that returns
this
. The JavaScript source code is like

L.DomEvent = {
// @function on(el: HTMLElement, eventMap: Object, context?: Object): this
on: function(e) {
// do stuff
return this;
}
}


See the detail source code.

I first write the definition as following

declare namespace L {
export namespace DomEvent {
export function on(el: HTMLScriptElement): this;
}
}


But the compiler throws an error with the message

error TS2526: A 'this' type is available only in a non-static member of a class or interface.


Although I can change the output from
this
to
any
(it works), I wonder if there is better solution to define the output.

Answer

Based on the code in github your declaration should look like this:

declare namespace L {
    export namespace DomEvent {
        export function on(el: HTMLElement, types: string, fn: Function, context?: any): typeof DomEvent;
    }
}

(code in playground)

You only return this as a type when you need it as polymorphic this types, but in this case the this that is returned is that DomEvent namespace, so we return typeof DomEvent.