Home > Software engineering >  TypeScript: type return of wrapper function to return type of function wrapped in closure
TypeScript: type return of wrapper function to return type of function wrapped in closure

Time:03-04

I have some iffy functions which need to be wrapped in try-catch-blocks. However, if they fail, I'm fine with having null as their return value. So, I decided to create a wrapper function which accepts a closure, and executes it. However, I'm struggling with the typing.

async function myStringFunction(myStringParam: string): Promise<string> {
    return Promise.resolve(`${myStringParam} is great!`)
}

async function myNumberFunction(myNumberParam: number): Promise<number> {
    return Promise.resolve(myNumberParam   1)
}

async function myArrayFunction(myArrayParam: string[]): Promise<string[]> {
    myArrayParam.push("another item")
    return Promise.resolve(myArrayParam)
}

async function doStuffOrReturnNull(myFunctionParam: () => any) {
    try {
        return await myFunctionParam()
    }
    catch(error) {
        return null
    }
}

async function mainFunction() {
    const myString = await doStuffOrReturnNull(() => myStringFunction("my input string"))
    const myNumber = await doStuffOrReturnNull(() => myNumberFunction(42))
    const myArray = await doStuffOrReturnNull(() => myArrayFunction(["whatever"]))
    console.log(myString, myNumber, myArray)
}

mainFunction()

The problem is, you guessed it: () => any. That way, I'm losing all typing information which the functions inside the closure has.

How can I type it so that the actual typing gets passed through?

In reality, I'm wrapping a third-party library here. So, the functions and return values could change over time. Hard-coding anything is absolutely out of question.

CodePudding user response:

You need to capture the type of the result using a type parameter:

async function doStuffOrReturnNull<T>(myFunctionParam: () => T) {
    try {
        return await myFunctionParam()
    }
    catch(error) {
        return null
    }
}

Playground Link

  • Related