[英]Typescript: Infer function argument
Ever Since TS 2.8, we can do the following: 从TS 2.8开始,我们可以执行以下操作:
type ArgType<F> = F extends (a: infer A) => any ? A : any
const fn: (s: string) => 500
ArgType<(typeof fn> // => string
Let's assume the following situation. 让我们假设以下情况。
type FunctionCollection = {
[key: string]: (s: ???) => any
}
const fnCol: FunctionCollection = {
someFn: (s: string) => 500
}
Question: Is there any way to replace ???
问题:有什么方法可以代替
???
(or the whole of FunctionCollection) with a type such that (或整个FunctionCollection)的类型
ArgType<(typeof fnCol)["someFn"]> 'equals' string
(The issue is that for example, if ??? = any
, we get any
) (问题是,例如,如果
??? = any
,我们得到any
)
Since the argument type can be different for each property of the type, you will need a type argument: 由于每个类型的属性的参数类型可以不同,因此您将需要一个类型参数:
type FunctionCollection<T> = {
[P in keyof T]: (s: T[P]) => any
}
Now to create such a variable you would need to specify the properties as the type argument to FunctionCollection
which is less then ideal: 现在要创建这样的变量,您需要将属性指定为
FunctionCollection
的类型参数,这比理想情况要差:
const fnColNoInference: FunctionCollection<{
someFn: string;
otherFn: number;
}> = {
someFn: (s: string) => 500,
otherFn: (s: number) => 500
}
A better approach is to use the inference behavior of functions to infer the type of the constant: 更好的方法是使用函数的推断行为来推断常量的类型:
function functionCollection<T>(args: FunctionCollection<T>) {
return args
}
const fnCol = functionCollection({
someFn: (s: string) => 500,
otherFn: (s: number) => 500
})
let d : ArgType<(typeof fnCol)["someFn"]> // is string
let d2 : ArgType<(typeof fnCol)["otherFn"]> // is number
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.