Skip to content

Better typing for keys when calling Object.entries #62152

@Gouvernathor

Description

@Gouvernathor

⚙ Compilation target

ES2022

⚙ Library

I think ES2022

Missing / Incorrect Definition

Object.entries

It is said to return [string, T][].
But if I have an object whose (non-Symbol) keys are typed as specific strings, it should reflect that these particular strings will be returned. Instead of string, it should be a new type parameter on the method, K extends string.

Current:
entries<T>(o: { [s: string]: T; } | ArrayLike<T>): [string, T][];
Proposed:
entries<K exends string, T>(o: { [s: K]: T; } | ArrayLike<T>): [K, T][];

Sample Code

type SideName = "left" | "right" | "top" | "bottom" | "front" | "back";
public setTextures(canvases: { readonly [K in SideName]: Canvas }) {
    const textures = {} as { [K in SideName]: number };
    for (const [key, canvas] of Object.entries(canvases)) {
        textures[key as SideName] = canvas.width;
    }
    return textures;
}

Replacing `key as SideName` with `key` fails, because the `key` coming out of the call to `Object.entries` is typed as `string` instead of `SideName`.

Documentation Link

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions