Sub topic 13
Pitfalls: Object.keys and runtime extra properties
This chapter assumes you know the basic assignability rules from the earlier chapters. These are that a value fits a type when it has at least the required members, that excess property checks apply only to fresh object literals, and that classes with private members behave nominally. You should also be comfortable with keyof and type assertions (as).
Structural typing has a consequence that surprises many developers. A value typed as Point is guaranteed to have x and y. It is not guaranteed to have only x and y. TypeScript's type system cannot see this difference, but your runtime code can.
Why Object.keys returns string[]
In the standard library, Object.keys has this signature:
keys(o: object): string[];You might expect Object.keys(p) to return (keyof Point)[] when p is a Point. TypeScript deliberately does not do that. Structural typing means a variable of type Point can hold any value that has at least x and y. The compiler knows only the type you declared. It does not know the exact type of the value you passed in.
The following code compiles without errors:
interface Point {
x: number;
y: number;
}
function sum(p: Point): number {
let total = 0;
for (const k of Object.keys(p)) {
// k is string, so p[k] would not compile without a cast
total += p[k as keyof Point];
}
return total;
}
const labeled = { x: 1, y: 2, label: "origin" };
console.log(sum(labeled)); // compiles, prints "3origin"The labeled variable is not a fresh object literal at the call site, so there is no excess property error. The loop visits x, y and label. The cast k as keyof Point tells the compiler that every key is "x" or "y", and that claim is false here. The function is declared to return number, but at runtime it returns the string "3origin", and the compiler reports nothing.
The cast is where the type system stops protecting you. If Object.keys returned (keyof Point)[], the compiler would accept this code without any cast and the bug would still exist, so the string[] return type is the more honest signature.
Where extra properties come from
Extra properties are common in ordinary programs. They are not an unusual edge case. Common sources are:
- Variables holding wider objects. The previous example is the typical case. Any non-fresh value skips the excess property check.
- Subclass instances. An instance of a class that adds fields is assignable to the base class's shape.
- Parsed data.
JSON.parsereturnsany. If you annotate the result asPoint, the compiler trusts you, and the actual payload can contain anything. - Spread copies.
{ ...p }has the static type ofpbut copies every own enumerable property of the runtime value. - Objects from libraries and APIs. A server response typed as
Usermay gain new fields when the API grows.
Here is a subclass example that gives a silently wrong answer:
interface Point {
x: number;
y: number;
}
class Point3D {
constructor(
public x: number,
public y: number,
public z: number,
) {}
}
function sum(p: Point): number {
let total = 0;
for (const k of Object.keys(p)) {
total += p[k as keyof Point];
}
return total;
}
console.log(sum(new Point3D(1, 2, 3))); // prints 6, but x + y is 3Point3D never declares that it implements Point, and it does not need to. Its shape fits, so the call compiles. The loop then includes z and the result is 6.
A related trap is for...in. The loop variable is also typed string, and the loop additionally visits enumerable properties inherited through the prototype chain. Object.keys returns only own enumerable properties, so it is usually the safer choice of the two.
Safer ways to iterate
The right fix depends on what you actually want. The options below are ordered from the most precise to the most permissive.
Name the properties you mean
If the type has a small, fixed set of properties, read them directly:
interface Point {
x: number;
y: number;
}
function sum(p: Point): number {
return p.x + p.y;
}
console.log(sum({ x: 1, y: 2 }));This is correct for any value that fits Point, extra properties included, because it never looks at them.
Keep one list of keys that the compiler checks
When you need to loop, keep a single list of keys and make the compiler verify it is complete. A Record<keyof Point, true> forces you to list every key of Point. A missing key and an unknown key are both errors:
interface Point {
x: number;
y: number;
}
const pointKeyMap: Record<keyof Point, true> = { x: true, y: true };
const pointKeys = Object.keys(pointKeyMap) as (keyof Point)[];
function sum(p: Point): number {
let total = 0;
for (const k of pointKeys) {
total += p[k];
}
return total;
}
console.log(sum({ x: 1, y: 2 }));The cast is still present, but it is now sound. The object being cast is a fresh literal that the compiler checked against Record<keyof Point, true>, so its keys are exactly x and y. If you later add z: number to Point, the declaration of pointKeyMap stops compiling until you add z.
Use a helper only when extras are acceptable
Sometimes you do want to visit whatever keys the value has, and you accept that they may be a superset. A small helper makes that decision visible in one place:
function keysOf<T extends object>(o: T): (keyof T)[] {
// Unsound by design: o may have keys beyond those in T.
return Object.keys(o) as (keyof T)[];
}This is fine for debugging output or for a generic that treats all keys the same way. It is a poor fit for arithmetic or anything where an unexpected key changes the result, as the sum examples show.
Copy only the fields you know
At a trust boundary, build a new object from the known fields. Extras are dropped, and nothing leaks into later code:
interface Point {
x: number;
y: number;
}
function toPoint(p: Point): Point {
return { x: p.x, y: p.y };
}
const withSecret = { x: 1, y: 2, token: "abc123" };
console.log(JSON.stringify(toPoint(withSecret))); // {"x":1,"y":2}
console.log(JSON.stringify(withSecret)); // includes the tokenThe second line shows another consequence of runtime extras. JSON.stringify, logging calls and anything else that walks the whole object will include data your types never mentioned. If you send a Point to a network call or a log, copy the known fields first.
Object.entries and interfaces
Object.entries has two overloads. One takes { [s: string]: T } and returns [string, T][]. The other takes {} and returns [string, any][].
Whether you get a useful value type depends on how the type was declared. Type aliases of object literal types are given an implicit index signature, so they match the first overload. Interfaces are not, so they fall through to the second overload and you get any:
type PointAlias = { x: number; y: number };
interface PointInterface {
x: number;
y: number;
}
declare const a: PointAlias;
declare const i: PointInterface;
const fromAlias = Object.entries(a); // [string, number][]
const fromInterface = Object.entries(i); // [string, any][]This is one of the few places where an interface and a type alias with the same members are not treated the same way. The any also hides the extra-properties problem: a string value from a surplus field would flow through as any without complaint. Treat the values from Object.entries as unchecked unless you have validated the input.
Common mistakes
| Mistake | What happens | Better approach |
|---|---|---|
| Casting `Object.keys(p)` to `(keyof T)[]` and using it for arithmetic | Extra properties are included, and results can be wrong or of the wrong type | Read named properties, or iterate a checked list of keys |
| Assuming a clean excess property check means no extras exist | The check covers only fresh literals, not variables, parameters or class instances | Build a new object from the known fields at boundaries |
| Using `for...in` over a typed object | Visits inherited enumerable properties, and the key is `string` | Prefer `Object.keys`, with the cast issues above in mind |
| Passing a wide object to `JSON.stringify` or a logger | Fields outside the declared type are serialized | Copy the known fields first |
| Trusting `[string, any][]` from `Object.entries` on an interface | Values lose their types | Use a type alias, or validate the values |
Summary of the rule
The compiler checks what a value must have. It never checks what a value must not have. That is the cost of accepting any value whose shape fits, and it is also what lets a Vec be passed where a Point is expected without an implements clause. When your code needs to know exactly which properties exist, keep that knowledge in one place: a literal list of keys, a validation function, or a copy of only the fields you want.
Exercise
A function takes p: Point (with x: number and y: number) and loops over Object.keys(p), using p[k as keyof Point] to compute a total. A caller passes { x: 1, y: 2, note: "a" } stored in a const variable. Does the call compile, and what does the function return?
Show answer
It compiles. The excess property check applies only to fresh object literals, and the argument is a variable. The loop visits x, y and note, so the total becomes 3 and then 3 + "a", which gives the string "3a". The function is declared to return number but returns a string, and the cast hides the problem.
Exercise
Why does TypeScript type Object.keys(o) as string[] instead of (keyof T)[], and how can you make a cast to keyof Point sound for a specific Point type?
Show answer
A value of type T may have more properties at runtime than T declares, because structural typing accepts any value whose shape fits. So the keys cannot be limited to keyof T. To make the cast sound, derive the key list from an object the compiler checks for exactness, such as const m: Record<keyof Point, true> = { x: true, y: true } followed by Object.keys(m) as (keyof Point)[]. Adding or removing a property on Point then produces a compile error until the record is updated.
Exercise
You receive a User typed as { id: string; name: string } from an API, and you want to log it. What can go wrong with console.log(JSON.stringify(user)), and how do you prevent it?
Show answer
The runtime object may carry extra fields, such as an email or a token, that the type does not mention, and JSON.stringify will include all of them. Prevent it by logging a copy built from the known fields, for example JSON.stringify({ id: user.id, name: user.name }).