TypeScript Version: 3.7.5
Code
type A = { b?: { c?: number } }
const a: A = { b: {c: 123} };
const isSafe = a && a.b && a.b.c
// if (a && a.b && a.b.c) { // <= works
if (isSafe) { // <= breaks
console.log(a.b.c); // (TS 2532) Object is possibly 'undefined'.
}
Expected behavior:
TS should check if isSafe protects against undefined
Actual behavior:
TS doesn't check isSafe
Output
"use strict";
const a = { b: { c: 123 } };
const isSafe = a && a.b && a.b.c;
// if (a && a.b && a.b.c) { // <= works
if (isSafe) { // <= breaks
console.log(a.b.c); // (TS 2532) Object is possibly 'undefined'.
}
Compiler Options
{
"compilerOptions": {
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"useDefineForClassFields": false,
"alwaysStrict": true,
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"downlevelIteration": false,
"noEmitHelpers": false,
"noLib": false,
"noStrictGenericChecks": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"esModuleInterop": true,
"preserveConstEnums": false,
"removeComments": false,
"skipLibCheck": false,
"checkJs": false,
"allowJs": false,
"declaration": true,
"experimentalDecorators": false,
"emitDecoratorMetadata": false,
"target": "ES2017",
"module": "ESNext"
}
}
Playground Link: Provided
TypeScript Version: 3.7.5
Code
Expected behavior:
TS should check if
isSafeprotects againstundefinedActual behavior:
TS doesn't check
isSafeOutput
Compiler Options
{ "compilerOptions": { "noImplicitAny": true, "strictNullChecks": true, "strictFunctionTypes": true, "strictPropertyInitialization": true, "strictBindCallApply": true, "noImplicitThis": true, "noImplicitReturns": true, "useDefineForClassFields": false, "alwaysStrict": true, "allowUnreachableCode": false, "allowUnusedLabels": false, "downlevelIteration": false, "noEmitHelpers": false, "noLib": false, "noStrictGenericChecks": false, "noUnusedLocals": false, "noUnusedParameters": false, "esModuleInterop": true, "preserveConstEnums": false, "removeComments": false, "skipLibCheck": false, "checkJs": false, "allowJs": false, "declaration": true, "experimentalDecorators": false, "emitDecoratorMetadata": false, "target": "ES2017", "module": "ESNext" } }Playground Link: Provided