Skip to content

"Object is possibly 'undefined'" after assignment with strictNullChecks #26599

@Asvel

Description

@Asvel

TypeScript Version: 3.1.0-dev.20180822

Search Terms:
Object is possibly 'undefined'.
strictNullChecks

Code

const objA = { a: 1, b: 2 };
type Key = keyof typeof objA;
const objB = {} as { [index in Key] ? : string[] };
for (const key of Object.keys(objA) as Key[]) {
  objB[key] = ['x'];
  console.log(objB[key][0]);
}

Expected behavior:
No error.

Actual behavior:

error TS2532: Object is possibly 'undefined'.

6   console.log(objB[key][0]);
                ~~~~~~~~~

Playground Link:
https://www.typescriptlang.org/play/index.html#src=const%20objA%20%3D%20%7B%20a%3A%201%2C%20b%3A%202%20%7D%3B%0D%0Atype%20Key%20%3D%20keyof%20typeof%20objA%3B%0D%0Aconst%20objB%20%3D%20%7B%7D%20as%20%7B%20%5Bindex%20in%20Key%5D%20%3F%20%3A%20string%5B%5D%20%7D%3B%0D%0Afor%20(const%20key%20of%20Object.keys(objA)%20as%20Key%5B%5D)%20%7B%0D%0A%20%20objB%5Bkey%5D%20%3D%20%5B'x'%5D%3B%0D%0A%20%20console.log(objB%5Bkey%5D%5B0%5D)%3B%0D%0A%7D

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions