打字稿动态推断类型

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");