Skip to content

TypeScript can't parse optional object when assigned to a variable  #36510

Closed
@bnbarak

Description

@bnbarak

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions