Skip to content

ES2019 Object.fromEntries uses PropertyKeys as mapped key type #31393

Closed
@AWare

Description

@AWare

TypeScript Version: 3.5.0-dev.20190514

Search Terms:
fromEntries
Code

// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
type T = {}

const a: { [key: string]: T } = { "key": {} }

const b: [string, T][] = Object.entries(a)

const c : {[key: number]: T; [key: string]: T } = Object.fromEntries(b)

const d : { [key: string]: T } = Object.fromEntries(b)

Expected behavior:

Compilation should fail because number is not a key of a.

edit: The return type of Object.fromEntries(b) should be inferred as d: { [key: string]: T } .

Actual behavior:

edit: The return type of Object.fromEntries(b) is {[key: number]: T; [key: string]: T } Adding an erroneous [key: number].

Object.fromEntries has type:

 fromEntries<T = any>(entries: Iterable<readonly [PropertyKey, T]>): { [k in PropertyKey]: T };

However if I make a second type parameter for fromEntries which extends PropertyKey and use that for the key type in forEntries:

 fromEntries<K extends PropertyKey, T = any>(entries: Iterable<readonly [K, T]>): { [k in K]: T };

I'm willing to make a PR for this if this sounds like a reasonable approach.

Playground Link:

Apologies, but I could not use es2019 in the playground.

Related Issues:

#30934

#30933 #25999

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions