Skip to content

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

Closed

Description

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

Activity

  1. nmain100 commented on Jan 29, 2020

    @nmain100

    Duplicate of #12184

  2. typescript-bot commented on Feb 6, 2020

    @typescript-bot
    Contributor

    This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

  3. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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