Skip to content

Unexpected narrowing of optional fields via Object.entries #61650

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

Open
defunctzombie opened this issue May 3, 2025 · 2 comments
Open

Unexpected narrowing of optional fields via Object.entries #61650

defunctzombie opened this issue May 3, 2025 · 2 comments

Comments

@defunctzombie
Copy link

defunctzombie commented May 3, 2025

πŸ”Ž Search Terms

object.entires incorrect type narrowed

πŸ•— Version & Regression Information

I can experience this on v5.8.3. I also checked back to 5.0.4 on the playground and see the same behavior

⏯ Playground Link

https://www.typescriptlang.org/play/?target=10&ts=5.8.3#code/GYVwdgxgLglg9mABMMAKYc4C5EG9EBGAhgE4D8OYIAtgQKYmIA+i4AJncDGHW4gL4BKPAChEiAPQTEUAJ4AHOgGcIJGPKgyAFtwDWS7TANHEAAwDaSqGrABzADSIqtBgF1zr04gDuWukiJoECIAGxDZRBhNCCIkejNLa24HJxp6RhZ2Tm5ed08xRAgEK0RSRgBeRAB5AgArOmgAOn8k5XRMQQBuAqKwJTgQukaQuFtUMq6RfhERFFRcAuISHCyuHjYprqA

πŸ’» Code

function fn(foo: { bar?: number | undefined }) {
  // typescript thinks _arr_ is `[string, number][]` when actually it is `[string, number | undefined][]`
  const arr = Object.entries(foo);
  console.log(arr);
}

fn({
  bar: undefined
});

πŸ™ Actual behavior

The type from Object.entries is narrowed

πŸ™‚ Expected behavior

Object.entries(foo) produces a type output that is [string, number | undefined][] when foo has type { bar?: number | undefined }

Additional information about the issue

No response

@defunctzombie defunctzombie changed the title Unexpected narrowing of optional fields when using Object.entries Unexpected narrowing of optional fields via Object.entries May 3, 2025
@MartinJohns
Copy link
Contributor

You need to enable exactOptionalPropertyTypes.

@defunctzombie
Copy link
Author

You need to enable exactOptionalPropertyTypes.

@MartinJohns could you elaborate on why that option would change the behavior here? From my perspective Object.entries has dropped the notion that one of the fields could be set to undefined and that would be a valid value for it. I understand the idea that it could be omitted entirely - but not being present is different than being set to undefined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants