I'm trying to understand why I keep getting this error from typescript.
PS. I know I would just use the boolean in this case and not create function, this question is more about typescript.
Not all code paths return a value.
Code:
const isCompleted = (completed: boolean) => {
if(completed) {
return true
} else if(!completed) {
return false
}
}
I don't get an error, when I just do this, but I shouldn't get an error either way.
const isCompleted = (completed: boolean) => {
if(completed) {
return true
} else {
return false
}
}
The reason is that every time you use a conditional, it forks the current execution into two possible branches (code paths).
The first conditional if (completed) {...}
forks into a path where you return true
, and another path (the remaining lines). The next conditional else if (!completed) {...}
forks into two more paths: one where you return false
, and another one where you never return any value (and in JavaScript, this implicitly returns undefined
).
As a human, you can read the code and see that the expression in each conditional is the same value: completed
(which is a boolean
and can only have two states), and you understand that there are no other possible paths for the code, but the TypeScript compiler does not currently infer this same relationship, so you must be more explicit about the code paths that you create using conditionals.