typescript 包装对象并仅代理它的一些方法

标签 typescript

当我在另一个类 Wrapper 中使用 Test 类时,我希望能够将方法代理到通用中的 test 实例方式 this.test[method]().

在这种情况下,我只想代理fly swimdrive(三者的签名相同)。 然而,问题出在 Test 类的其他方法中,这就是 TypeScript 提示的地方。

在第一个 //1. addEventListener 中,如果我尝试使用 keysof 那么 TypeScript 会因为方法签名而提示。

在第二个 //2. addEventListener 我试图通过 Pick 实用程序类型创建一个新类型 CustomMethods,但后来我得到了错误 CustomMethod 不能用作索引类型

有没有办法在--strict模式下编译这段代码?

class Test {
  fly(location: string, listener: Function) {}
  swim(location: string, listener: Function) {}
  drive(location: string, listener: Function) {}

  stopFlying(birds:number[]){}
  stopDriving(racers:boolean[]){}

}

// pick some of the methods from the Test type
type CustomMethods = Pick<Test, "fly" | "swim"| "drive">;


class Wrapper {
  public name: string;
  public test: Test;
  constructor(t:Test) {
    this.name = "event";
    this.test = t
  }

  // 1.
  addListener(method: keyof Test, listener: Function) {
    this.test[method](this.name, listener);
  }

  // 2.
  addListener(method: CustomMethods, listener: Function) {
    this.test[method](this.name, listener);
  }
}

typescript playground demo

最佳答案

你需要keyof Pick<Test, "fly" | "swim"| "drive"> ,不只是 Pick<Test, "fly" | "swim"| "drive"> .

关于 typescript 包装对象并仅代理它的一些方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57976606/

相关文章:

angular - 拖动以在页面周围移动组件?

html - 我们可以从 Angular 应用程序中排除 tsconfig.spec.json

typescript - 如何存储对构造函数的引用?

typescript - 如何保留隐式键名称类型作为接口(interface)的一部分,同时仍然在 TS 中指定值类型?

angular - 当用户单击 mat-calendar 中的月份导航时,如何检索月份和年份值?

javascript - 使用 Typescript 展平来自 Apollo/Hasura GraphQL 查询的结果

javascript - 使用枚举形式 setInterval() 导致异常?

node.js - 多对多关系的正确文件夹结构

javascript - 如何在js中创建 TreeView

typescript - 如何避免TypeScript中的动态keyof对象分配错误