obj[prop] || (obj[prop] = {}): Object is possibly 'undefined' -- Documentation?
See original GitHub issueSuggestion
It would be great to have TS documentation about “Object is possibly ‘undefined’. ts(2532)” common cases that most everyone will run into and be puzzled about. The TS playground below shows such an example when using code like: obj[prop] || (obj[prop] = {})
and when most everyone would expect obj[prop]
not to be flagged as ‘undefined’.
TS Playground: link
🔍 Search Terms
Object is possibly ‘undefined’. ts(2532) TypeScript Object property assignment TypeScript Object OR assignment undefined
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn’t be a breaking change in existing TypeScript/JavaScript code
- This wouldn’t change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn’t a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript’s Design Goals.
⭐ Suggestion
I would like to see common cases documentation about the “Object is possibly ‘undefined’. ts(2532)” error. Maybe it exists and I could not find it.
📃 Motivating Example
I see many issues filed related to ts(2532) because of the current limitations of TypeScript.
💻 Use Cases
See TS Playground link.
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
@MartinJohns: I will give it a go next week. I admit I am still fairly new to TS but I’ll try to gather examples from the filed issues.
This isn’t really about TS2532 specifically but about type narrowing in general–TS doesn’t treat any check involving
obj[key]
as a type guard unlesskey
is a literal. This does come up often though, see e.g. #48227 or #48203, and is a known limitation of control-flow-based type narrowing so it should probably be mentioned in the FAQ at this point.