You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
strictNullChecks - property accesses on string index signatures should narrow #17960
// process.env is defined as { [key: string]: string | undefined } in @types/node// Expectedconsole.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 hereconsole.log(process.env.MY_ENV_VAR.length);// TS2532: Object is possibly 'undefined'}/* ------------------------------------------------------------------------------------- */constcollection: {[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.
changed the title [-]strictNullChecks - unexpected behavior with string index types[/-][+]strictNullChecks - property accesses on string index signatures should narrow[/+]on Jun 28, 2018
Activity
mhegazy commentedon Aug 22, 2017
The second issue is tracked by #13778.
ithinkihaveacat commentedon Aug 27, 2017
It's also surprising that assigning the (theoretically) type narrowed object to a different variable removes the error:
vis seemingly equivalent toprocess.env.MY_ENV_VAR; why do they behave differently?[-]strictNullChecks - unexpected behavior with string index types[/-][+]strictNullChecks - property accesses on string index signatures should narrow[/+]thorn0 commentedon May 7, 2019
Another seemingly related error (TS 3.4.5):
playground
jakebailey commentedon Jul 9, 2023
Just looking at old issues; this one was fixed by #19838.