Object#entries and Object#values doesn't consider optional properties as potentially undefined
eliasm307 opened this issue ยท 3 comments
Bug Report
๐ Search Terms
- Object entries optional properties
- Object values optional properties
๐ Version & Regression Information
- This changed between versions 4.2.3 and 4.3.5
โฏ Playground Link
- 4.2.3 Playground link producing type error as expected
- 4.3.5 Playground link not producing type error anymore
๐ป Code
// without tsconfig.json#exactOptionalPropertyTypes enabled, optional properties can exist with `undefined`
const obj: {foo?: string, bar?: string} = {foo: undefined, bar: undefined}
Object.entries(obj).forEach(([key, value]) => {
const str: string = value; // value should be recognised as potentially undefined
})
Object.values(obj).forEach(value => {
const str: string = value; // value should be recognised as potentially undefined
})๐ Actual behavior
From v4.3 it doesnt consider optional object properties as potentially undefined (with exactOptionalPropertyTypes disabled) when using Object#entries or Object#values
๐ Expected behavior
Optional properties should mean the value when using Object#entries or Object#values is potentially undefined when exactOptionalPropertyTypes is disabled, as undefined could be assigned to the optional properties.
This allows TS to compile code with potential runtime issues from using optional properties as if they were always defined.
Duplicate of #48587. The solution to this is to enable exactOptionalPropertyTypes.
Thanks @MartinJohns ! Unfortunately, enabling exactOptionalPropertyTypes in the code base im working on would require a lot of fixes so it's not an easy option and difficult to justify the work required.
I understand the concerns in the linked issue about the behaviour potentially causing issues to existing code, however I'm not clear if the change in behaviour in v4.3 was intentional or a regression?
Anyway, it would be nice if there was a way to atleast get a warning about things that might be undefined when iterating over object properties. An option could be to tie different behaviour depending on the value passed to the exactOptionalPropertyTypes option, similar to how different values change the behaviour of allowUnreachableCode. So:
- undefined value would be the existing default behaviour
- true would be where undefined can't be assigned to optional properties
- false would allow assigning undefined to optional properties and also show warnings for potentially undefined property value usages
This is the intended behavior as Martin explained.
I don't see much appetite from our side for bifurcation that flag's behavior. This is the first request I've seen where someone only wants some of its implications and it's been available for a pretty long time by now.