Typescript如何声明一个返回要调用的对象的方法(此)

时间:2019-01-08 02:30:49

标签: javascript typescript

如何为 on 函数编写声明。 on 函数必须根据其所调用的对象返回动态类型。

function on(type, handler) {
    this.addEventListener(arguments);

    return this;
}

var element = document.getElementById('elm');
var request = new XMLHttpRequest();

element.on = on; // => element.on(t,cb) must return element 
request.on = on; // => request.on(t,cb) must return request 

这是我的d.ts(这只是示例,在ThisType上不正确)

declare function on<K extends keyof WindowEventMap>(type: string, handler: 
(this: ThisType, ev: WindowEventMap[K]) => any): ThisType;

我不知道Typescript是否还有另一个关键字可以解决此问题。 ( ThisCaller

1 个答案:

答案 0 :(得分:1)

TypeScript具有称为polymorphic this types的功能,可在此处使用。

但是,此作业

element.on = on;

将被标记为错误,因为在TypeScript中,您不能仅通过分配给对象的属性来添加任意属性。

您可以通过添加类型安全性的方式来实现此目的,方法是添加一个函数,该函数会将on属性添加到对象,并返回相同的对象但声明了适当的类型,并告诉编译器它现在具有{ {1}}属性:

on