Typed Object.keys and Object.entries
Helpers that keep key types instead of widening to string, for objects you know the shape of.
- TypeScript
- GreenSnippets
- MIT
- Executed with Node.js 22 (type stripping)
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
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.
Related snippets
- TypeScript Tested
Type-safe event emitter
An event emitter whose event names and payloads are checked by the compiler through a generic map type.
- TypeScript Tested
Generic groupBy with key inference
Group an array into a Record by a property or function while keeping the item type.
- TypeScript Tested
Debounce with preserved argument types
A debounce function whose returned function keeps the parameter types and exposes cancel() and flush().
- JavaScript Tested
Pick and omit object keys
Build a new object with only some keys, or without some keys, without mutating the original.

