英文:
Typescript Generics: type safe generics for parameters of a method of an object
问题
以下是您要翻译的内容:
我正在尝试使用泛型来从单个包装函数调用对象的函数以及其相应的参数。
这是我想要实现的内容:
class Class1 {
method() {}
}
class Class2 {
method(x: string) {}
}
class Class3 {
method(x: number, y: string) {}
}
// 有效
wrapper(new Class1());
// 有效
wrapper(new Class2(), 'hello');
// 有效
wrapper(new Class3(), 10, 'hello');
// 无效
wrapper(new Class3(), '10', 'hello');
以下是我的尝试:
function wrapper<
M extends { method: F },
F extends (..._: any[]) => any,
P extends Parameters<F>
>(m: M, ...p: P) {
m.method(...p);
}
这段代码有效,但不提供参数 p
的类型安全性。我可以传递对于函数 m.method
无效的参数。
英文:
I am trying to use generics to invoke a function of an object with its respective parameters from a single wrapper function.
Here is what I am trying to achieve:
class Class1 {
method() {}
}
class Class2 {
method(x: string) {}
}
class Class 3 {
method(x: number, y: string) {}
}
// valid
wrapper(new Class1());
// valid
wrapper(new Class2(), 'hello');
// valid
wrapper(new Class3(), 10, 'hello');
// invalid
wrapper(new Class3(), '10', 'hello');
Here is my attempt:
function wrapper<
M extends { method: F },
F extends (..._: any[]) => any,
P extends Parameters<F>
>(m: M, ...p: P) {
m.method(...p);
}
This works, but does not provide type safety on the parameter p
. I am able to pass parameters that are not valid for the function m.method
.
答案1
得分: 1
Since the compiler doesn't have anywhere to infer F
from (other type parameters are not used as inference sites), it defaults to its constraint of (...args: any[]) => any
. You really only need 1 generic type parameter here:
function wrapper<
F extends (...args: any[]) => any,
>(m: { method: F }, ...p: Parameters<F>) {
// ^^^^^^^^^ inference point for F
m.method(...p);
}
英文:
Since the compiler doesn't have anywhere to infer F
from (other type parameters are not used as inference sites), it defaults to its constraint of (...args: any[]) => any
. You really only need 1 generic type parameter here:
function wrapper<
F extends (...args: any[]) => any,
>(m: { method: F }, ...p: Parameters<F>) {
// ^^^^^^^^^ inference point for F
m.method(...p);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论