Typescript: Object entry remains typed as undefined after assignment

Created on 25 Aug 2019  路  4Comments  路  Source: microsoft/TypeScript


TypeScript Version: 3.7.0-dev.20190824


Search Terms:
Object is possibly undefined
TS2532

Code

interface IData {
  data: number;
}

interface IMyObject {
  [index: string]: IData | undefined;
}

const myObject: IMyObject = {};
const objectKey = 'something';

myObject[objectKey] = {
  data: 5
}

console.log(myObject[objectKey].data); // TS2532: Object is possibly 'undefined'

Expected behavior:
Code compiles without error.

Actual behavior:
Error: TS2532: Object is possibly 'undefined'. on myObject[objectKey]

Playground Link:
http://www.typescriptlang.org/play/index.html#code/JYOwLgpgTgZghgYwgAgJIBE5jsg3gKGWQBMs4AuZEAVwFsAjaAbnwF999RJZEVUBZAJ4B5egCsICMHkLIA2qGIQAHpQDOYKKADmAXUoYyyAD7JqIJTFARiLdvgQB7EBuS0R4yWANDREqcgAvHisLE4u0o6eUgDSEIJByADkao60EGAAFjpJLPjufl5yUf5gcYK6iQREpNiUAKxsHOGpADYQAHStjtoAFAXRYMWD5bodtXAAlExAA

Related Issues:

13778, #17960, #26599, #29642

It seems related issues have been around for a long time, in addition issue #26599 was closed as a "wontfix". This is weird to me because it seems Typescript should be able to detect that objectKey has not changed between the object assignment and query.

Duplicate

Most helpful comment

If the key is truly variable, then this is related to #31445: TS isn't equipped to understand that two mentions of obj[key] access the same property in both places; since it doesn't even know that, it doesn't make sense to perform any narrowing on it.

All 4 comments

If anyone else is looking for a workaround,

interface IData {
  data: number;
}

interface IMyObject {
  [index: string]: IData | undefined;
}

const myObject: IMyObject = {};
const objectKey = 'something';

myObject.something = {
  data: 5
}

console.log(myObject.something.data);

Playground

Just don't use string literals/constants. Use dot notation instead.

Just don't use string literals/constants. Use dot notation instead.

Good solution, but doesn't work when objectKey is a variable :)

What I posted is just a demonstration of the issue, in most cases the object keys are not constant but variables or parameters passed to a function.

If the key is truly variable, then this is related to #31445: TS isn't equipped to understand that two mentions of obj[key] access the same property in both places; since it doesn't even know that, it doesn't make sense to perform any narrowing on it.

Yep, duplicate of #31445 (and some others).

Was this page helpful?
0 / 5 - 0 ratings