0
votes

I want to use a strict return type statement in Typescript.
When I write a function with a single if-then-else statement, the TS Linter of vscode is smart enough to see accept my return value:

IfThenElseWorks

If I try to do the same if a single .then().catch() block, in which there aren't any other possibilites for the function to go, my linter won't accept the return type.

Error Message in VsCode

Returning the promise won't work aswell (as intended)

Return promise

I also checked with a .finally() statement, which doesn't work aswell and isn't intended to be used in my situation.

Source:

var myPromise = new Promise(function (resolve, reject) {
    if (Math.round(Math.random()) == 1) {
        resolve("yay")
    } else {
        reject("nay")
    }
});

function returnYayOrNay(): string {
    myPromise
        .then((result) => {
            return result
        })
        .catch((result) => {
            return result
        })
}

Edit 1: I want to return a string as in Picture2

2
A promise is async in nature, you cannot return synchronously from it.Ingo Bürk
Not a dupe, but you definitely need to read it: stackoverflow.com/questions/14220321/…Jamiec
@IngoBürk You want to say that including a minor async call would need a rewrite of my complete sync codebase?Ernst Robert
There's async await. I'm telling you that you cannot synchronously return a result that is only known asynchronously. We can't travel through time.Ingo Bürk

2 Answers

2
votes

By default, the return type of a promise is Promise<{}>. So, You can typecast the promise return value.

var myPromise = new Promise<string>(function (resolve, reject) {
   if (Math.round(Math.random()) == 1) {
      resolve("yay")
   } else {
      reject("nay")
   }
});

In the Above example, the return value becomes Promise<string>.

1
votes

The problem with the returnYayOrNay function is that it does not return a string. When you use then and catch of a promise you are passing in a function (an anonymous arrow function =>). So return result just return from this anonymous function.

My guess is that you want to return the value of myPromise. You can't return this directly as when returnYayOrNay is called the value of myPromise may not yet available. So returnYayOrNay should also return a promise.

Also myPromise is typed by default to Promise{} as typescript can't infer the type of the result based on the usage of resolve and reject

That being said, you have several options :

Return the new promise crated by the then, catch calls:

function returnYayOrNay() {
    return myPromise
        .then((result) => {
            return result
        })
        .catch((result : string) => {
            return result
        })
}

Use async/await

async function returnYayOrNay() {
    try{
        return await myPromise;
    }catch(e) {
        return e as string;
    }
}