Microsoft/TypeScript

Functions in mixins with return type 'this' are typed as 'any' in declaration files

Open

#51.206 geöffnet am 17. Okt. 2022

Auf GitHub ansehen
 (0 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)TypeScript (6.726 Forks)batch import
BugDomain: Declaration EmitHelp Wanted

Repository-Metriken

Stars
 (48.455 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 6T 17h) (9 gemergte PRs in 30 T)

Beschreibung

Bug Report

🔎 Search Terms

mixin declaration this

🕗 Version & Regression Information

4.5.4, but active in 4.8.4

  • This is the behavior in every version I tried

⏯ Playground Link

Playground link with relevant code

💻 Code

(slightly edited example from mixins doc)

class Sprite {
  name = "";
 
  constructor(name: string) {
    this.name = name;
  }
}

type Constructor = new (...args: any[]) => {};
 
function Scale<TBase extends Constructor>(Base: TBase) {
  return class Scaling extends Base {
    _scale = 1;
 
    setScale(scale: number): this {
      this._scale = scale;
      return this;
    }
  };
}

// this results in 'setScale(scale: number): any' in .d.ts
export default Scale(Sprite);

// this is typed correctly ('setScale(scale: number): this')
// const scaledSprite = Scale(Sprite);
// export default scaledSprite;

🙁 Actual behavior

return type of setScale on the class with mixin applied is typed as any

declare const _default: {
    new (...args: any[]): {
        _scale: number;
        setScale(scale: number): any;
    };
} & typeof Sprite;

🙂 Expected behavior

return type of setScale on the class with mixin applied should be this

declare const _default: {
    new (...args: any[]): {
        _scale: number;
        setScale(scale: number): this;
    };
} & typeof Sprite;

In the playground, if Scale(Sprite) is assigned to a variable first before being exported, the types are correct. However, it seems that if the mixin is declared in a separate file and used in another file, the function is always typed incorrectly as any

Contributor Guide