Skip to content

Object entry remains typed as undefined after assignment #33073

@Ionaru

Description

@Ionaru

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.

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