首页 > 解决方案 > 如何表示 TS 装饰器的输出类的类型

问题描述

以下代码来自 TS 文档

function classDecorator<T extends { new (...args: any[]): {} }>(
  constructor: T
) {
  return class extends constructor {
    newProperty = "new property";
    hello = "override";
  };
}

@classDecorator
class Greeter {
  property = "property";
  hello: string;
  constructor(m: string) {
    this.hello = m;
  }
}
const g = new Greeter("world");
console.log(g.newProperty) // =>>>> ERROR for type check, but correct in runtime

如何表达装饰类的类型?

更准确地说,我希望智能感知看到g.newProperty

标签: typescriptoop

解决方案


还有一个叫做 的概念mixin,一个返回修改后的类 TypeScript 的函数能够为类的返回类型建议正确的道具

function Mixin<T extends { new (...args: any[]): object }>(BaseClass: T) {
  return class extends BaseClass {
    // The following constructor signature is a must for a mixin
    // TypeScript error tells it explicitly
    constructor(...args: any[]) {
      super(...args)
      // Additional stuff
    }
    // Additional functionality here
  }
}

class A {}

const ModifiedA = Mixin(A);

const ModifiedAObject = new ModifiedA(/* params */);

推荐阅读