Microsoft/TypeScript

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

Open

#51,206 创建于 2022年10月17日

在 GitHub 查看
 (0 评论) (0 反应) (0 负责人)TypeScript (6,726 fork)batch import
BugDomain: Declaration EmitHelp Wanted

仓库指标

Star
 (48,455 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 9 个 PR)

描述

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

贡献者指南