Skip to content
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

Utility type: Object entries tuple #32771

nhardy opened this issue Aug 9, 2019 · 1 comment


Copy link

commented Aug 9, 2019

Search Terms

Utility type, object entries, tuple, mapped type


An Entries<T> utility type that constructs a union of all object entry tuples of type T in lib.es5.d.ts.

 * Construct a union of all object entry tuples of type T
type Entries<T> = {
    [P in keyof T]: [P, T[P]];
}[keyof T];

Use Cases

I understand the history behind why Object.entries provides string as the key type rather than the actual keys (because there may exist more actual keys that those defined in the type). I refer to discussion here.

Sometimes, however, we can be confident that only properties defined in the type will be present at runtime, and have found that a utility type like this can be helpful to more strictly define such types, particularly in tests.


const expected = {
   foo: "foo",
   bar: "Bar",
   baz: "BAZ",
} as const;

(Object.entries(expected) as Entries<typeof expected>).forEach(([input, output]) => {
  // where `myFunction`'s first parameter only accepts `"foo" | "bar" | "baz"` (or a superset)
function thatAcceptsJsxAttributeTuples(attributes: readonly Entries<JSX.IntrinsicElements["path"][]>): void {
  // ...


My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

This comment has been minimized.

Copy link

commented Aug 14, 2019

I was about to report this as a bug. I'll leave the demonstration that I coded up, distilled from my personal use case:

type O = { [key: string]: unknown };
type B<A extends O> = { [K in keyof A]: A[K] };

class Test<A extends O> {
  public constructor(private a: A) {}

  public test() {
    const b = {} as B<A>;
    for (const [key, value] of Object.entries(this.a)) {
      b[key] = value; // error: Type 'string' cannot be used to index type 'B<A>'.
      b[key as keyof A] = value as A[keyof A];
    return b;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
3 participants
You can’t perform that action at this time.