Skip to content

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

Closed
@VianneyCarton

Description

@VianneyCarton

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.

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