Typescript学习: 记录一下 dialog标签在 typescript中一些新属性报错情况的处理

typescript的lib.dom.d.ts 里有 open/openModal/close 等属性还没有
更新于: 2024-05-10 11:31:08

看一下现在的 lib.dom.d.ts 里的内容

/** @deprecated - this is not available in most browsers */
interface HTMLDialogElement extends HTMLElement {
    addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
    removeEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}

我实现的的组件里调用了 interface 里没有的方法

效果如下, 我的组件 里调用了,openModal/close 方法

class Component extends React.Component {
  updateComponent(inProps) {
    const { value } = inProps;
    if (value && !this.value) this.dom.showModal();
    if (!value && this.value) this.dom.close();
  }
}

解决方案如下

不过这个实现在 jest测试的时候,还会有问题,暂不修复

interface HTMLDialogElementExt extends HTMLDialogElement {
  open: boolean;
  close: () => void;
  showModal: () => void;
}

class. 的属性报错

TS2564: Property ve has no initializer and is not definitely assigned in the constructor.
"strictPropertyInitialization": false

参考