[英]Typescript dynamically infer type
我有一些函数存储在一个变量中,并想将它传递给另一个函数,我希望这个函数将重用它的参数。 但它不起作用。 查看示例
// I want pass this function (and steal its parameters dynamically)
const a = (a: string) => { }
const b = (...args: Parameters<typeof a>) {
}
const c = (c) => (...args: Parameters<typeof c>) => {
}
const d = <T>(...args: Parameters<T>) => {
}
// this works:
b()
// this doesn't work, need to make it working
// it doesn't work because for TS is c literally ANY here (c) => (...args: Parameters<typeof c>) => {}
c(a)()
// this works but i don't was this solution becuase would be ugly and long
d<typeof a>(1)
// in real world the last solution would look like
Foo.make<typeof Some.Function.GetIt>(Some.Function.GetIt, ...)
这应该适合你:
const a = (a: string) => { }
const c = <F extends (...args: any) => any>(c: F) => (...args: Parameters<F>) => {
}
// c(a) is inferred to (a: string) => void
c(a)("test");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.