TypeScript example

How to loop through an object in TypeScript

9 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

Use for...of over Object.entries(): for (const [key, value] of Object.entries(obj)). On a Record<string, number> the value comes out as a number, so it is type-checked like any other number. The key is always a string, and so is every key from Object.keys: TypeScript returns string[], not (keyof T)[], because an object can carry more keys at runtime than its type lists.

The loops are the JavaScript ones: Object.entries, Object.keys, Object.values and for...in. The JavaScript version of this page covers how they behave at runtime, inherited keys and key order included. What TypeScript adds is the types of what comes out, and that is where the questions start: why Object.keys(user) is string[] instead of the keys of User, why user[key] is an error in a strict project, and why the values from an interface come out as any.

This page's compiler runs without strict. Every example below also passes with strict on, as in most projects, and the strict-mode messages quoted in the notes come from TypeScript 5.9 with --strict. Each example runs on this page: hit Run, then edit the code and run it again.

1for...of with Object.entries()Recommended

Give the object a dictionary type, such as Record<string, number> or an index signature, and Object.entries returns [string, number][]. Destructure each pair in the loop head and both names are typed: the key as string, the value as the value type. When the values are objects, you can destructure those too, and their properties keep their types. break and continue work, because it is an ordinary for...of over an array.

entries.ts
// A dictionary type: any string key, a number for every value
const stock: Record<string, number> = { apple: 12, banana: 0, cherry: 7 };

for (const [fruit, count] of Object.entries(stock)) {
    // fruit is a string and count is a number, so number methods type-check
    if (count === 0) continue;
    console.log(`${fruit.padEnd(6)} ${count.toFixed(1)}`);
}

// Object values keep their type too, so you can destructure them in the loop head
interface Account {
    role: 'admin' | 'dev';
    active: boolean;
}
const accounts: Record<string, Account> = {
    ada: { role: 'admin', active: true },
    linus: { role: 'dev', active: false },
};
for (const [name, { role, active }] of Object.entries(accounts)) {
    console.log(name, role.toUpperCase(), active ? 'active' : 'inactive');
}

// One side only: Object.keys gives string[], Object.values gives number[]
const total = Object.values(stock).reduce((sum, n) => sum + n, 0);
console.log(Object.keys(stock), total);

Output

Prints apple 12.0 and cherry 7.0 (banana is skipped by the continue), then ada ADMIN active and linus DEV inactive, then [ 'apple', 'banana', 'cherry' ] 19. count.toFixed(1) and role.toUpperCase() are checked against the real types, so a typo such as count.toFixd stops the build instead of failing at runtime. To set up the dictionary type itself, see create a dictionary.

2Object.keys() returns string[], not keyof T

The first surprise comes when the object has a fixed shape, like an interface. The keys of User are 'name' | 'city', yet Object.keys(user) is typed string[], and so is the variable of a for...in loop. Pass such a key anywhere that expects keyof User and the checker refuses. This example fails on purpose: press Run to see the error.

keys-string.ts
interface User {
    name: string;
    city: string;
}

function field(user: User, key: keyof User): string {
    return user[key];
}

const user: User = { name: 'Ada', city: 'London' };

// Object.keys(user) is string[], not ('name' | 'city')[]
for (const key of Object.keys(user)) {
    console.log(key, field(user, key));
}

Output

Nothing runs. The compiler reports error TS2345: Argument of type 'string' is not assignable to parameter of type 'keyof User'. The more common form of the same problem is indexing: user[key] with a string key. On this page that compiles and quietly gives any, but with strict on (as in most projects) both Object.keys and for...in loops fail with error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User'. followed by No index signature with a parameter of type 'string' was found on type 'User'. Section 3 shows why TypeScript does this and which fix to pick.

3Why: an object can have more keys than its type

TypeScript types are structural: any object with an x and a y number is a valid Point, including one with extra properties. So at runtime, Object.keys on a Point can return keys the type never mentions, and string[] is the honest answer. The usual fix, Object.keys(obj) as (keyof T)[], is a promise that no extra keys exist. The example keeps that promise once and breaks it once.

extra-keys.ts
interface Point {
    x: number;
    y: number;
}

// The cast most answers suggest: "these keys are keyof T"
function keysOf<T extends object>(obj: T): (keyof T)[] {
    return Object.keys(obj) as (keyof T)[];
}

function sum(p: Point): number {
    let total = 0;
    for (const key of keysOf(p)) {
        total += p[key]; // type-checks: key is 'x' | 'y', p[key] is a number
    }
    return total;
}

console.log(sum({ x: 1, y: 2 }));

// A wider object is still a valid Point: it has every property a Point needs
const labelled = { x: 1, y: 2, z: 100, label: 'A' };
const result = sum(labelled);
console.log(result, typeof result);
console.log(keysOf<Point>(labelled));

// Safe: loop over the keys you know, not the ones the object happens to have
const POINT_KEYS = ['x', 'y'] as const;
function safeSum(p: Point): number {
    let total = 0;
    for (const key of POINT_KEYS) total += p[key];
    return total;
}
console.log(safeSum(labelled));

Output

The plain point gives 3. The wider object gives 103A string: the loop visited z and label too, so a function typed to return a number returned the string 103A, and the checker could not see it. The keys it really had were [ 'x', 'y', 'z', 'label' ]. Looping over a fixed list of known keys, declared with as const, gives 3 again (see create a union type from an array for that pattern). The cast is fine when you build the object yourself and nothing wider can reach it. Passing the object literal straight to sum would be caught, because fresh literals get an excess-property check: error TS2353: Object literal may only specify known properties, and 'z' does not exist in type 'Point'. A variable that is already wider skips that check, as here.

4Object.entries() on an interface gives any

Object.entries only knows the value type when the object fits { [key: string]: T }. A type alias for an object does, because TypeScript gives object type aliases an implicit index signature. An interface does not, so the call falls back to the overload that returns [string, any][]. The two declarations below are identical except for the keyword, and only one of them is checked.

interface-any.ts
interface Product {
    name: string;
    price: number;
}
type ProductShape = {
    name: string;
    price: number;
};

const lamp: Product = { name: 'Lamp', price: 25 };
const desk: ProductShape = { name: 'Desk', price: 140 };

// From an interface, every value is any: the checker lets anything through
for (const [key, value] of Object.entries(lamp)) {
    try {
        console.log(key, value.toUpperCase());
    } catch (err) {
        console.log(key, 'threw:', (err as Error).message);
    }
}

// From a type alias, the value is string | number, so you must narrow first
for (const [key, value] of Object.entries(desk)) {
    const shown = typeof value === 'string' ? value.toUpperCase() : value.toFixed(2);
    console.log(key, shown);
}

// For an interface, annotate the pairs yourself (the same promise as keysOf)
type Entry = [keyof Product, Product[keyof Product]];
for (const [key, value] of Object.entries(lamp) as Entry[]) {
    console.log(key, typeof value);
}

Output

The interface loop compiles value.toUpperCase() for both values, prints name LAMP, and then price threw: value.toUpperCase is not a function at runtime, because the price is a number. The type-alias loop sees string | number, so the code has to narrow with typeof before calling a method, and it prints name DESK and price 140.00. Calling Object.entries<string | number>(lamp) does not help an interface: it fails with Index signature for type 'string' is missing in type 'Product'. The last loop annotates the pairs instead and prints name string and price number. Like the cast in section 3, that annotation trusts the object to have no extra keys.

5for...in and keyof

for...in also gives string keys on a concrete type, for the same reason. Inside a generic function it is different: for obj: T, the key is typed Extract<keyof T, string>, so obj[key] type-checks even with strict on. That makes a generic helper the cleanest place for a for...in loop. Remember that it also visits inherited enumerable keys; the JavaScript page covers that and the Object.hasOwn guard.

for-in.ts
// In a generic function, the for...in key is typed as a key of T
function describe<T extends object>(obj: T): string {
    const parts: string[] = [];
    for (const key in obj) {
        // key: Extract<keyof T, string>, so obj[key] type-checks under strict too
        parts.push(`${key}=${String(obj[key])}`);
    }
    return parts.join(' ');
}
console.log(describe({ host: 'localhost', port: 8080, tls: false }));

// On a concrete type the key is a plain string: cast it to index the object
interface Config {
    host: string;
    port: number;
}
const config: Config = { host: 'localhost', port: 8080 };
for (const key in config) {
    const k = key as keyof Config;
    console.log(k, config[k]);
}

// Class instances: for...in sees the fields, not the methods on the prototype
class Server {
    host = 'localhost';
    port = 8080;
    url(): string {
        return `http://${this.host}:${this.port}`;
    }
}
const server = new Server();
for (const key in server) console.log('field:', key);
console.log(Object.keys(server), server.url());

Output

The generic helper prints host=localhost port=8080 tls=false with no cast. The concrete loop needs key as keyof Config to index the object under strict, and prints host localhost and port 8080. On a class instance, for...in lists only host and port: methods live on the prototype and are not enumerable, and Object.keys agrees with [ 'host', 'port' ]. Getters are left out the same way.

6Map an object without losing its keys

The JavaScript idiom for mapping an object is a round trip: Object.entries, an array method, then Object.fromEntries. It works in TypeScript, but the result is typed { [k: string]: V }, so the original key names are gone and any key type-checks. A small generic mapValues with a mapped type, { [K in keyof T]: U }, keeps them.

map-object.ts
const cents = { apple: 120, bread: 350, milk: 99 };

// Object.fromEntries returns { [k: string]: string }: the key names are lost
const loose = Object.fromEntries(
    Object.entries(cents).map(([item, c]) => [item, (c / 100).toFixed(2)]),
);
console.log(loose.apple, loose.tomato); // tomato compiles, and is undefined

// A typed mapValues keeps the keys: { apple: string; bread: string; milk: string }
function mapValues<T extends object, U>(
    obj: T,
    fn: (value: T[keyof T], key: keyof T) => U,
): { [K in keyof T]: U } {
    const out = {} as { [K in keyof T]: U };
    for (const key of Object.keys(obj) as (keyof T)[]) {
        out[key] = fn(obj[key], key);
    }
    return out;
}

const dollars = mapValues(cents, (c) => (c / 100).toFixed(2));
console.log(dollars);
console.log(dollars.milk.padStart(6, '.'));

// filter works the same round trip, and also comes back as a plain dictionary
const cheap = Object.fromEntries(Object.entries(cents).filter(([, c]) => c < 200));
console.log(cheap);

Output

loose.tomato compiles and prints undefined next to 1.20. The typed version prints { apple: '1.20', bread: '3.50', milk: '0.99' } and ..0.99, and its result type has exactly the three keys, so dollars.tomato would not compile: error TS2339: Property 'tomato' does not exist on type '{ apple: string; bread: string; milk: string; }'. Inside mapValues the keys come from the same cast as section 3; the function only reads the object, so an extra key would just be copied along. The filtered dictionary is { apple: 120, milk: 99 }, typed { [k: string]: number }, which is right: you can't know which keys survive a filter until it runs.

7Which should you use?

MethodKey typeValue typeBest for
for (const [k, v] of Object.entries(obj))stringThe value type (any for an interface)The default loop over a dictionary or Record
Object.keys(obj) / Object.values(obj)string[]The value typeCounting, summing, filter/some/reduce
Object.keys(obj) as (keyof T)[]keyof T (a promise)T[keyof T]Objects you build yourself, with no extra keys
for (const key of KEYS) with as constThe listed keysT[key]Fixed shapes: exact and safe
for (const key in obj) in a generic functionExtract<keyof T, string>T[key]Generic helpers; also visits inherited keys
for (const [k, v] of map)KVA Map: any key type, insertion order

Frequently asked questions

Why does Object.keys return string[] instead of keyof T in TypeScript?

Because TypeScript types are structural: a value typed Point can be any object with at least the properties of Point, so at runtime Object.keys may return keys the type does not list. Typing the result as (keyof T)[] would let p[key] claim a type the value does not have. When you know the object has no extra keys, cast: Object.keys(obj) as (keyof T)[]. When the shape is fixed, loop over an as const list of keys instead.

How do I fix "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type"?

That is TS7053, reported with strict (or noImplicitAny) on when you index an object with a string key, usually from Object.keys or for...in. Pick one: loop with Object.entries(obj) so you never index at all; narrow the key with a cast such as key as keyof User when the object has no extra keys; or give the object a dictionary type with an index signature, such as Record<string, number>, so any string key is allowed.

How do I loop through a dictionary in TypeScript?

Type the dictionary as Record<string, V> (or { [key: string]: V }) and loop with for (const [key, value] of Object.entries(dict)). The key is a string and the value is a V. For keys that are not strings, or when you need insertion order for every key, use a Map<K, V> instead and loop it directly with for (const [key, value] of map).

How do I loop through a Map in TypeScript?

A Map is iterable, so for (const [key, value] of map) works with no helper, and both names get the map's K and V types. map.keys(), map.values() and map.entries() give iterators of the keys, the values and the pairs, and map.forEach((value, key) => ...) passes the value first. Object.entries(map) does not work: a Map keeps its entries internally, not as properties, so it returns [].

Why is the value any when I use Object.entries on an interface?

Object.entries has a typed overload for objects with a string index signature and an untyped one that returns [string, any][]. A type alias for an object type gets an implicit index signature, so it matches the typed overload and the value becomes the union of the property types. An interface does not, so it falls back to any. Declare the shape with type, or annotate the pairs: Object.entries(obj) as [keyof T, T[keyof T]][].

Should I use for...in or Object.keys in TypeScript?

Prefer Object.keys or Object.entries with for...of: they return own properties only, and the loop supports break and continue. for...in also visits inherited enumerable properties, and outside a generic function its key is a plain string. Inside a generic function over T, for (const key in obj) types the key as Extract<keyof T, string>, which is convenient for small helpers.

Run it yourself

Open any of these in the full TypeScript editor to tweak, run and share.

TypeScript playground