Typescript动态推断类型

问题描述 投票:-1回答:1

我将一些函数存储在变量中,并希望将其传递给另一个函数,并且我希望该函数将重用其参数。但这是行不通的。查看示例

// 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, ...)
typescript inferred-type
1个回答
0
投票

这应该为您解决:

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");
© www.soinside.com 2019 - 2024. All rights reserved.