Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript typescript动态类方法的类型_Javascript_Typescript_Class_Types_Interface - Fatal编程技术网

Javascript typescript动态类方法的类型

Javascript typescript动态类方法的类型,javascript,typescript,class,types,interface,Javascript,Typescript,Class,Types,Interface,我试图构建一个类,在构造函数阶段构建一些动态方法,一切都很好,但是VS代码自动建议对动态方法不起作用?我们应该怎么做? 这是你的电话号码 我也试过界面,但还是没有成功 export default class A { private version = 1; get getVersion() { return this.version; } private actions = ["approve", "edit", "delete"]; constructor() {

我试图构建一个类,在构造函数阶段构建一些动态方法,一切都很好,但是VS代码自动建议对动态方法不起作用?我们应该怎么做? 这是你的电话号码

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

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  

你可以这样做。。。但它真的相当粗糙。像这样的元编程不可能完全进行类型检查。这个解决方案有一个简单的例子

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

private actions = ["approve", "edit", "delete"] as const;
type _A = {
    [K in A['actions'][number]]: (route: string) => void
}
接下来,创建一个映射类型,描述您的
forEach
方法添加到该类型的内容

private actions = ["approve", "edit", "delete"] as const;
type _A = {
    [K in A['actions'][number]]: (route: string) => void
}
请注意,这必须是
类型
。它不能是
接口

最后,添加扩展此类型别名的接口。我原以为TS会在这里对我大喊大叫,但显然这没关系

export default interface A extends _A {
}