Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Asvel opened this issue Aug 22, 2018 · 3 comments
Closed

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

Asvel opened this issue Aug 22, 2018 · 3 comments
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@Asvel
Copy link

Asvel commented Aug 22, 2018

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

@ghost ghost added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Aug 22, 2018
@ghost
Copy link

ghost commented Aug 22, 2018

Control flow analysis only works for known keys (like obj.x) and not computed keys. So it won't work for an object key stored in a variable.

@Asvel
Copy link
Author

Asvel commented Aug 23, 2018

Thanks.

@Asvel Asvel closed this as completed Aug 23, 2018
@iwe7
Copy link

iwe7 commented Sep 4, 2018

tsconfig -> strictNullChecks:false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

2 participants