#How do I best avoid this return type error within a loop?

17 messages · Page 1 of 1 (latest)

acoustic tendon
#

I have a function, which will either throw an error, or return a string. When put in a loop, TypeScript doesn't understand what's being returned. Am I missing something, or do I just have to ignore this line?

const MAX_RETRIES = 2;

function doSomething(): string {
    let count = 0;
    while (count < MAX_RETRIES) {

        try {

            // Do some other things
            return "Hello World!" // Return the actual data

        } catch (e) {
            if (count == MAX_RETRIES) {
                throw e
            } else count++;
        }

    }
}
lunar osprey
#

well, if the code throws every time and you reach the maximum amount of retries, then the catch block doesn't do anything

#

and the function exists without returning anything

#

but you said your function should retrun a string, so there is the problem

#

basically, there is code path that is not covered

#

(TS doesn't actually take the loop into acount, just that there is no return in the catch>else block)

acoustic tendon
#

:/

#

I guess I'll just have to put it outside the catch block

modern gate
#

I mean if you just change while (...) to while (true) it works.

#

TS can't really reason about your code on the logical level, only on the type level.

lunar osprey
lunar osprey
modern gate
#

No, I don't think TS cares about infinite loops.

lunar osprey
#

oh, right

modern gate
#

You can also write it recursion style:

const MAX_RETRIES = 2;

function doSomething(retries = MAX_RETRIES): string {
    if (!retries) throw new Error()
    
    try {
        return "Hello World!"
    } catch (e) {
        return doSomething(retries - 1)
    }
}
lunar osprey
#

!ts

wicked pantherBOT
#
const MAX_RETRIES = 2;

function doSomething(retries = MAX_RETRIES): string {
    if (!retries) throw new Error()
    
    try {
        return "Hello World!"
    } catch (e) {
        return doSomething(retries - 1)
    }
}