TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

In JS, property assignment incorrectly overrides accessor from base

Open jeremy-rifkin opened this issue 4 years ago • 1 comments

Bug Report

🔎 Search Terms

inferring properties from assignments

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about inferring properties from assignments

⏯ Playground Link

N/A

💻 Code

Steps to reproduce:

test.js

export class Element {
  /**
   * @returns {String}
   */
  get textContent() {
    return  ''
  }
  set textContent(x) {}
  cloneNode() { return this}
}
export class HTMLElement extends Element {}
export class TextElement extends HTMLElement {
  get innerHTML() { return this.textContent; }
  set innerHTML(html) { this.textContent = html; }
  toString() {
    const outerHTML = toString.call(this.cloneNode());
    return outerHTML.replace(/></, `>${this.textContent}<`);
  }
}

Run

tsc --declaration --allowJs test.js --outDir types

🙁 Actual behavior

types/test.d.ts is generated as:

export class Element {
    set textContent(arg: string);
    /**
     * @returns {String}
     */
    get textContent(): string;
    cloneNode(): Element;
}
export class HTMLElement extends Element {
}
export class TextElement extends HTMLElement {
    set innerHTML(arg: any);
    get innerHTML(): any;
    textContent: any;
    toString(): any;
}

This is incorrect:

error TS2610: 'textContent' is defined as an accessor in class 'HTMLElement', but is overridden here in 'TextElement' as an instance property.

2     textContent: any;
      ~~~~~~~~~~~

🙂 Expected behavior

types/test.d.ts should be:

export class Element {
    set textContent(arg: string);
    /**
     * @returns {String}
     */
    get textContent(): string;
    cloneNode(): Element;
}
export class HTMLElement extends Element {
}
export class TextElement extends HTMLElement {
    set innerHTML(arg: any);
    get innerHTML(): any;
    toString(): any;
}

Workaround:

  set innerHTML(html) {
    /** @type {string} */
    this.textContent = html;
  }

jeremy-rifkin avatar Oct 16 '22 15:10 jeremy-rifkin

Alternative workaround: set innerHTML(/** @type {string} */ html) { this.textContent = html; }

MartinJohns avatar Oct 16 '22 16:10 MartinJohns