【发布时间】:2020-11-20 17:54:07
【问题描述】:
我在尝试使用 TypeScript 正确地将方法添加到 HTMLElement 时遇到了两个问题:
- 我不知道如何添加方法到我不拥有的现有类(没有通过“扩展”创建新类,所以我不必在我创建 HTMLElement 的任何地方添加注释)。
- 我不确定是否有一种 更简单 的方式来引用“this”而不明确指出类型 via(this 作为 HTMLElement)。
例子:
let newProps = {
tag: {
get: function(): any {
return (typeof (<unknown>this as HTMLElement).getAttribute('tagged') != 'undefined') //Any better way to handle this?
},
set: function(tagged: boolean) {
if (tagged) {
(<unknown>this as HTMLElement).removeAttribute('tagged');
} else {
(<unknown>this as HTMLElement).setAttribute('tagged', '');
}
},
},
};
Object.defineProperties(HTMLElement.prototype, newProps);
/*
... define an HTMLElement as a button
*/
//@ts-ignore
myButton.tag = true; //error: Property 'tag' does not exist on type 'HTMLElement' //How to add new method to HTMLElement without using "extends" to create a new class??
感谢您的任何建议!
【问题讨论】:
-
更改托管对象的原型被认为是一种非常糟糕的做法。为什么你想要它而不是简单地接受一个元素作为其参数的函数?
-
如果我可以在按钮上获取/设置简单的属性,只会使代码更清晰、更简单。不那么冗长。
-
“只会让代码更干净、更简单”——不会更简单:无法判断该函数的来源。
-
在什么情况下?我正在编写所涉及的方法供我自己使用。不确定我是否关注这个问题。
标签: typescript