推断功能链中的参数类型 [英] Infer parameter types in function chain
问题描述
我正在尝试制作一个自制的函数映射链.问题是,我想确保在映射链中键入保持一致.我的问题是我不知道如何写 f(x:T)=>U
I'm trying to make a home made function mapping chain. Thing is, I want to make sure typing stays consistent trough the mapping chain. My problem is that I don't know how to write f(x:T) => U
有关我要执行的操作的正确示例:
For a proper example of what I'm trying to do:
function myChainer<T>(args:T){
return {
map:(innerFuction:(payload: T) => unknown){
return myChainer(innerFuction(args))
}
}
}
现在,如果我跑步
myChainer(0)
.map((args1) => {
return doSomething(args1) ? "a" : "b"
})
.map((args2) => {
return doSomething2(args2) ? true : false
})
第一个 map
将知道 args1
的类型是 Number
,但是第二个不会知道 args2的类型
是 string
.而且,正如预期的那样,后续的链接函数将不知道其各自参数的类型.应该用什么替换 unknown
,以便每个链接的函数根据先前链接的函数的返回类型找出其参数的类型?
The first map
will know that the type of args1
is Number
but the second one wont know that the type of args2
is string
. And, as expected, subsequent chained functions wont know the types of their respective arguments. With what should unknown
be replaced with so that every chained function figures out the type of its arguments based on the return type of the previously chained function?
推荐答案
您需要使用通用类型参数来引用 innerFunction
的返回类型,以便随后提供递归引用 myChainer
时,该类型将输入TS.
You need to use a generic type parameter to refer to whatever the return type of the innerFunction
is, so that you can then provide that type to TS when you recursively refer to myChainer
.
这里是这样的:
function myChainer<T>(args:T){
return {
map<U>(innerFuction:(payload: T) => U) {
return myChainer<U>(innerFuction(args))
}
}
}
这篇关于推断功能链中的参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!