Typescript:推断函数参数
从TS 2.8开始,我们可以执行以下操作:Typescript:推断函数参数,typescript,functional-programming,conditional-types,Typescript,Functional Programming,Conditional Types,从TS 2.8开始,我们可以执行以下操作: type ArgType<F> = F extends (a: infer A) => any ? A : any const fn: (s: string) => 500 ArgType<(typeof fn> // => string 问题:有没有办法将?(或整个FunctionCollection)替换为 ArgType<(typeof fnCol)["someFn"]> 'equals
type ArgType<F> = F extends (a: infer A) => any ? A : any
const fn: (s: string) => 500
ArgType<(typeof fn> // => string
问题:有没有办法将?
(或整个FunctionCollection)替换为
ArgType<(typeof fnCol)["someFn"]> 'equals' string
ArgType“等于”字符串
(问题是,例如,如果
??=any
,我们得到any
)由于参数类型对于类型的每个属性都可能不同,因此您需要一个类型参数:
type FunctionCollection<T> = {
[P in keyof T]: (s: T[P]) => any
}
更好的方法是使用函数的推断行为来推断常量的类型:
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
函数集合(args:functionCollection){
返回参数
}
const fnCol=函数集合({
someFn:(s:string)=>500,
其他fn:(s:编号)=>500
})
设d:ArgType//为字符串
设d2:ArgType//为数字
不错!我已经在我的案例中使用了第一种解决方案,但我来这里是为了更好的解决方案。我喜欢第二个!然而,我意识到这并不能解决我的实际问题。我将发布一个跟进。
const fnColNoInference: FunctionCollection<{
someFn: string;
otherFn: number;
}> = {
someFn: (s: string) => 500,
otherFn: (s: number) => 500
}
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