Microsoft/TypeScript

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

Open

#51,206 opened on 2022幎10月17日

GitHub で芋る
 (0 comments) (0 reactions) (0 assignees)TypeScript (6,726 forks)batch import
BugDomain: Declaration EmitHelp Wanted

Repository metrics

Stars
 (48,455 stars)
PR merge metrics
 (平均マヌゞ 6d 17h) (30d で 9 merged PRs)

説明

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

コントリビュヌタヌガむド