Skip to content

strictNullChecks - property accesses on string index signatures should narrow #17960

Closed

Description

TypeScript Version: 2.6.0-dev.20170819

Code

// process.env is defined as { [key: string]: string | undefined } in @types/node

// Expected
console.log(process.env.MY_ENV_VAR.length);  // TS2532: Object is possibly 'undefined'

if (process.env.MY_ENV_VAR) {
  // Unexpected - process.env.MY_ENV_VAR is defined here
  console.log(process.env.MY_ENV_VAR.length); // TS2532: Object is possibly 'undefined'
}

/* ------------------------------------------------------------------------------------- */

const collection: { [id: string]: string } = {};

console.log(collection.someVar.length); // No error

Expected behavior:
When using strictNullChecks :

  • The compiler should not emmit an TS2532: Object is possibly 'undefined' error when accessing an index of an object defined as { [key: string]: string | undefined } inside a guard.
  • The compiler should emmit an error when accessing an index of an object defined as { [key: string]: string } inside a guard without checking it first.

Actual behavior:
Please see code sample.

Activity

  1. mhegazy commented on Aug 22, 2017

    @mhegazy
    Contributor

    The second issue is tracked by #13778.

  2. ithinkihaveacat commented on Aug 27, 2017

    @ithinkihaveacat

    It's also surprising that assigning the (theoretically) type narrowed object to a different variable removes the error:

    if (process.env.MY_ENV_VAR) {
      console.log(process.env.MY_ENV_VAR.length); // ERROR
    }
    
    const v = process.env.MY_ENV_VAR;
    if (v) {
      console.log(v.length); // NO ERROR
    }

    v is seemingly equivalent to process.env.MY_ENV_VAR; why do they behave differently?

  3. changed the title [-]strictNullChecks - unexpected behavior with string index types[/-] [+]strictNullChecks - property accesses on string index signatures should narrow[/+] on Jun 28, 2018
  4. thorn0 commented on May 7, 2019

    @thorn0

    Another seemingly related error (TS 3.4.5):

    declare const foo: {
        [id: string]: {
            bar?: {
                baz?: boolean;
            }
        }
    };
    const a1 = foo.id && foo.id.bar && foo.id.bar.baz; // works fine
    const key = 'id';
    const a2 = foo[key] && foo[key].bar && foo[key].bar.baz; // error: Object is possibly 'undefined'

    playground

  5. jakebailey commented on Jul 9, 2023

    @jakebailey
    Member

    Just looking at old issues; this one was fixed by #19838.

  6. 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

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions