Course contentsShow
← TypeScript
Lesson 1007 of 1,79623. Type AssertionsFree lesson

Working with Object.keys and Iteration

Asserting key types when iterating over objects where TypeScript treats keys as strings despite known shape.

Working with Object.keys and Iteration

What you'll learn: How to handle TypeScript's string-typed keys when iterating over objects with known shapes, and when type assertions become necessary.

The Problem: Object.keys Returns string[]

When you use Object.keys() on an object with a well-defined type, you might expect TypeScript to infer the exact property names. Surprisingly, it doesn't:

type User = {
  name: string;
  age: number;
};

const user: User = {
  name: "Alice",
  age: 30
};

const keys = Object.keys(user); // Type: string[]

Even though user has a known shape, keys is typed as string[], not ("name" | "age")[]. This creates friction when you try to use those keys to access properties safely.

Why TypeScript Does This

TypeScript is being defensively correct. At runtime, objects can have additional properties not reflected in their declared type:

const user: User = { name: "Alice", age: 30 };
(user as any).role = "Admin"; // Runtime addition

Object.keys(user); // Returns ["name", "age", "role"]

If TypeScript assumed keys were only "name" | "age", it would lie about what actually exists at runtime.

The Assertion Solution

When you're certain about your object's shape, you can assert the key type:

const keys = Object.keys(user) as (keyof User)[];

keys.forEach(key => {
  console.log(user[key]); // Now TypeScript knows key is valid
});

The assertion tells TypeScript to trust that these keys match the type's known properties.

Alternative: Type Guards

For stricter validation, check keys explicitly:

function isUserKey(key: string): key is keyof User {
  return key === "name" || key === "age";
}

Object.keys(user).forEach(key => {
  if (isUserKey(key)) {
    console.log(user[key]); // Safe access
  }
});

Key Takeaway: Object.keys() returns string[] to reflect runtime reality; use as (keyof T)[] assertions when you control the object's shape completely, but understand this is an escape hatch that bypasses structural checks.