【问题标题】:How to add to HTMLElement properly with TypeScript?如何使用 TypeScript 正确添加到 HTMLElement?
【发布时间】:2020-11-20 17:54:07
【问题描述】:

我在尝试使用 TypeScript 正确地将方法添加到 HTMLElement 时遇到了两个问题:

  1. 我不知道如何添加方法到我不拥有的现有类(没有通过“扩展”创建新类,所以我不必在我创建 HTMLElement 的任何地方添加注释)。
  2. 我不确定是否有一种 更简单 的方式来引用“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


【解决方案1】:

需要添加到全局HTMLElement接口。

工作示例

// Augment the global 
interface HTMLElement {
  tag: boolean
}


// Now no error 
declare const myButton: HTMLElement;
myButton.tag = true; // No error

更多

【讨论】:

  • 这适用于新属性,但是 TypeScript 现在会为原生属性/方法引发错误,例如 removeAttribute(): (this as HTMLElement).removeAttribute('disabled'); //TS:“HTMLElement”类型上不存在属性“removeAttribute”。
猜你喜欢
  • 2022-12-11
  • 1970-01-01
  • 2021-08-01
  • 2023-04-03
  • 2016-10-04
  • 1970-01-01
  • 2022-10-14
  • 2016-12-11
  • 2021-04-24
相关资源
最近更新 更多