简体   繁体   English

推断 function 链中的参数类型

[英]Infer parameter types in function chain

I'm trying to make a home made function mapping chain.我正在尝试制作一个自制的 function 映射链。 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我的问题是我不知道如何写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))
       }
    }
}

Now, if I run现在,如果我跑

myChainer(0)
.map((args1) => {
    return doSomething(args1) ? "a" : "b"
})
.map((args2) => {
    return doSomething2(args2) ? true : false
})

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 .第一个map会知道args1的类型是Number但第二个不会知道args2的类型是string And, as expected, subsequent chained functions wont know the types of their respective arguments.而且,正如预期的那样,后续的链接函数不会知道它们各自的 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?应该用什么来替换unknown ,以便每个链接的 function 根据先前链接的 function 的返回类型找出其 arguments 的类型?

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 .您需要使用泛型类型参数来引用innerFunction的返回类型,以便在递归引用myChainer时可以将该类型提供给 TS。

Here is what that would look like:这就是它的样子:

function myChainer<T>(args:T){
    return {
       map<U>(innerFuction:(payload: T) => U) {
           return myChainer<U>(innerFuction(args))
       }
    }
}

Here you have:在这里你有:


function myChainer<T>(args: T) {
    return {
        map: <R,>(innerFuction: (payload: T) => R) => {
            return myChainer(innerFuction(args))
        }
    }
}

const foo = (arg: number) => arg.toString()
const bar = (arg: string) => Promise.resolve(parseInt(arg, 10))
const baz = (arg: Promise<number>) => arg


const result = myChainer(0)
    .map(arg => foo(arg)) // arg -> number
    .map(arg => bar(arg)) // arg -> string
    .map(arg => baz(arg)) // arg -> Promise<number>
    .map(arg => foo(arg)) // expected error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM