Description
TypeScript Version: 3.4.5
Search Terms: Object is possibly 'undefined'
Code
function Sum(A?: number) {
const AisUndefined: boolean = typeof A === "undefined";
if (AisUndefined) {
return 'is undefined';
}
const sum: number = A + 10; //Error here: "Object is possibly 'undefined'"
return sum;
}
Expected behavior: As I assign the condition typeof A === "undefined"
in the constant AisUndefined
and make a if statement to return a string in case of A
is definitely undefined, in the constant sum
, there should be no problem making a sum of A
with a number assuming that A
is definitely not undefined as the code reach there, after the if statement.
Actual behavior: When I try to make a sum with A
and a number, and probably any other operation that takes on that A
is not undefined, typescript identifies this as an error, saying that Object is possibly 'undefined'
, basically ignoring the return
inside the if statement.
Note: If I replace the constant AisUndefined
by their own condition, like:
if (typeof A === "undefined") {
return 'is undefined';
}
Therefrom, the error disappears.
Playground Link: https://www.typescriptlang.org/play//#src=function%20Sum(A%3F%3A%20number)%20%7B%0D%0A%20%20%20%20const%20AisUndefined%3A%20boolean%20%3D%20typeof%20A%20%3D%3D%3D%20%22undefined%22%3B%0D%0A%0D%0A%20%20%20%20if%20(AisUndefined)%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20'is%20undefined'%3B%0D%0A%20%20%20%20%7D%0D%0A%0D%0A%20%20%20%20const%20sum%3A%20number%20%3D%20A%20%2B%2010%3B%0D%0A%20%20%20%20return%20sum%3B%0D%0A%7D (You will have to check the strictNullChecks
option to get this error)
Related Issues: