microsoft/TypeScript

Incorrect type inference in Object.entries and Object.values if type has optional value

Opened this issue ยท 1 comments

Crinax commented

๐Ÿ”Ž Search Terms

object.entries, object.values, type inference, incorrect type inference,

๐Ÿ•— Version & Regression Information

  • This changed between versions 4.5.5 and 6.0 (nightly)

โฏ Playground Link

https://www.typescriptlang.org/play/?noUncheckedIndexedAccess=true&noPropertyAccessFromIndexSignature=true#code/C4TwDgpgBAyg9gWwgaQiAzlAvFA5AQ1ygB88AjI03AY1wG4AoUSKANXwBsBXaHdYAE4BLAHYBzRgybhoAFQj8A8mQBW2KAG8GUHVADaAayijYiFGnQBdAPwAuNpx6MAvlI4RgUCPflLV6rV0ofHsuEQATCAAzUQhwhlcpAHok2AALOC4OcKgyaD1+YXEAGihC0TESKDDImJE4yz1LBndPCABREUEhBXVlFQhqYAA6CC7hBQAKCABKOigU-XKSsu7xRuaGRZgMrJy8qEnlytIa6NjwmaaWjy92bl6cfsGRgDdHKdn5xeOmoA

๐Ÿ’ป Code

type SomeKeys = 'a' | 'b' | 'c';
type Value = string;


type TestObj = {
    [k in SomeKeys]?: Value;
}

let e: TestObj = {
    a: undefined
}


// Should be [string, string | undefined][]
let eEntries = Object.entries(e); // [string, string][]

// Should be (string | undefined)[]
let eValues = Object.values(e); // string[]

๐Ÿ™ Actual behavior

  • Type of result of Object.entries is a [string, T]
  • Type of result of Object.values is a T[]

๐Ÿ™‚ Expected behavior

  • Type of result of Object.entries should be a [string, T | undefined] if optional property exists
  • Type of result of Object.values should be a (T | undefined)[] if optional property exists

Additional information about the issue

No response

Duplicate of #52045.