Skip to content
GreenSnippets

Typed Object.keys and Object.entries

Helpers that keep key types instead of widening to string, for objects you know the shape of.

TypeScript
function typedKeys<T extends object>(obj: T): (keyof T)[] {
  return Object.keys(obj) as (keyof T)[];
}

function typedEntries<T extends object>(obj: T): { [K in keyof T]: [K, T[K]] }[keyof T][] {
  return Object.entries(obj) as { [K in keyof T]: [K, T[K]] }[keyof T][];
}

Example / expected output

Output
const prices = { apple: 1.2, pear: 2 };
for (const [name, price] of typedEntries(prices)) {
  // name: "apple" | "pear", price: number
}

How it works

Object.keys returns string[] because objects may have extra properties at runtime. When you know the object is exactly its declared type (for example a constant), these wrappers give you precise keys back. Do not use them on objects from untrusted input.