【问题标题】:typescript type of dynamic class methodstypescript 类型的动态类方法
【发布时间】:2020-04-03 00:03:21
【问题描述】:

我正在尝试构建一个在构造函数阶段构建一些动态方法的类,一切正常,但是 VS Code 自动建议不适用于动态方法?我们应该怎么做? 这是codeSandBox

我也试过interface,但还是没有成功

export default class A {
  private version = 1;
  get getVersion() {
    return this.version;
  }
  private actions = ["approve", "edit", "delete"];
  constructor() {
    this.actions.forEach(
      method =>
        (A.prototype[method] = route => {
          console.warn(method + " called");
        })
    );
  }
}

const B = new A();
console.warn(B.getVersion);
console.warn(B.approve()) // auto suggestion not available here  

【问题讨论】:

    标签: javascript typescript class types interface


    【解决方案1】:

    你可以这样做......但它真的很hacky。像这样的元编程是不可能进行完全类型检查的。这是带有此解决方案的playground

    首先告诉 TS,actions 是一个常量数组,这样可以缩小类型。

    private actions = ["approve", "edit", "delete"] as const;
    

    接下来,创建一个映射类型,描述您的 forEach 方法添加到类型中的内容。

    type _A = {
        [K in A['actions'][number]]: (route: string) => void
    }
    

    请注意,这必须是type。不能是interface

    最后,添加一个扩展此类型别名的接口。我预计 TS 会在这里对我大吼大叫,但显然这没关系。

    export default interface A extends _A {
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-20
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多