Say we pass in w
to WhatToGet
.
Then it won’t execute return
*.
That’s a problem.
*Well technically it will automatically return something but IDK what it is in TypeScript. In Python, that would be None
which is TypeScript’s null
.
So if I put an else, it will work?
You need to always return something no matter what happens in the function. And they have to be the same type.
So something like this:
function foo(x: number): boolean {
if (x== 0) {
return true
}
}
Will give an error, because x
can be 1, so it won’t execute return true
.
Something like this:
function foo(x: number): boolean {
if (x== 0) {
return true
} else {
return false
}
}
Will be syntactically correct. But notice how true
and false
are both booleans
. You couldn’t do this:
function foo(x: number): boolean {
if (x== 0) {
return true
} else {
return "bad value"
}
}
But you could do
if (ReturedValue == 0) {
splash ("Bad Vaue")
}
Right?
Are you in a function? You will still need to return a value.
No, separate.
Yes, but you still have the problem with your original function.
Yes If your function sometimes returns a value then It will get confused, If you use (if returned value == 0 then “bad value…”) that will be fine.
But you always have to return or not return.
Oh, I fixed that with the else statment.
At all times, you have to put return blocks at the end of a function if you have another return block at the end