TypeScript Version: 4.0.0-beta
Search Terms:
Expected behavior:
When a created variable contains a null check, using that boolean should be sufficient for safe access to the variable.
Actual behavior:
TypeScript needs an additional null check.
Related Issues:
Code
export default function foo(a: {b: boolean} | undefined) {
const isNull = a == null;
if (isNull) {
return;
}
// Object is possibly 'undefined'.
return a.b
}
Output
export default function foo(a) {
const isNull = a == null;
if (isNull) {
return;
}
return a.b;
}
Compiler Options
{
"compilerOptions": {
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"alwaysStrict": true,
"esModuleInterop": true,
"declaration": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"moduleResolution": 2,
"target": "ES2017",
"jsx": "React",
"module": "ESNext"
}
}
Playground Link: Provided
My apologies if this issue already exists, I couldn't find it with my search terms! Thanks for your help!
Duplicate of #12184.
You can use a type guard instead:
function isNullish<T>(x: T | null | undefined): x is null | undefined {
return x == null;
}
declare const x: number | undefined;
if (!isNullish(x)) {
x // number
}
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.
Most helpful comment
You can use a type guard instead: