gpt4 book ai didi

typescript - 在 TypeScript 中处理动态 `.apply()` 使用的正确方法是什么?

转载 作者:搜寻专家 更新时间:2023-10-30 21:31:45 25 4
gpt4 key购买 nike

考虑 following code ,它定义了一个具有三种方法的对象。每个方法采用不同数量的参数,然后底部的代码通过 apply() 调用其中一个方法(动态地,基于变量的值)用args数组。

class Obj {
a() {
return 0;
}
b(one: string) {
return 1;
}
c(one: string, two: string) {
return 2;
}
}

const obj = new Obj();

function callMethod(method: keyof Obj, ...args: any[]): void {
obj[method].apply(obj, args) // Errors
}

callMethod('a');

编译上述代码时,TypeScript 报错,大概是因为 args数组的长度可以为 0,但 b()c()方法需要一些参数:

The 'this' context of type '(() => number) | ((one: string) => number) | ((one: string, two: string) => number)' is not assignable to method's 'this' of type '(this: Obj) => number'.
Type '(one: string) => number' is not assignable to type '(this: Obj) => number'.

此示例说明了基于某个变量的值动态调用方法名称的 JavaScript 问题的用例。

我如何向类型检查器发出信号:

  • 任何时候我调用方法a() args 的长度将为 0
  • 任何时候我调用方法b() args 的长度将是 1
  • 任何时候我调用方法c()长度为 2

或者,如果有人知道解决此问题的更好方法,我愿意接受建议!

最佳答案

您可以使用 Parameters<T>以通用方式提取函数参数的辅助类型:

function callMethod<T extends keyof Obj>(
method: T,
...args: Parameters<Obj[T]>
): void {
(obj[method] as any).apply(obj, args);
}

关于typescript - 在 TypeScript 中处理动态 `.apply()` 使用的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58243361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com