Sub topic 7
Inherited keys and null-prototype objects
This chapter assumes you know basic TypeScript types, interfaces, and type aliases. It also assumes you know how to read JavaScript properties with dot and bracket notation, and how union types and undefined work. You should have seen index signatures such as Record<string, number>. The chapter shows how a typed dictionary can return values that its type does not describe, and how to prevent that.
Why a dictionary can contain keys you never added
A plain object is not an empty container. An object created with {} has a hidden link to Object.prototype, called its prototype. When you read a property that the object does not have itself, JavaScript follows that link and looks on the prototype. Object.prototype defines toString, valueOf, constructor, hasOwnProperty, and a few others, so every plain object appears to have those keys.
TypeScript does not model this. A Record<string, number> says that every string key maps to a number. For the key "toString" the runtime value is a function. The type is wrong for that key, and the compiler cannot tell you.
A bug the compiler cannot see
Word counting is a common use for a dictionary. This version looks correct and type-checks:
const counts: Record<string, number> = {};
for (const word of ["apple", "constructor", "apple"]) {
counts[word] = (counts[word] ?? 0) + 1;
}
console.log(counts["apple"]); // 2
console.log(counts["constructor"]); // "function Object() { [native code] }1"On the first "constructor", the read counts["constructor"] finds the inherited Object function. It is neither undefined nor null, so ?? 0 does not apply. The expression then becomes Object + 1, which JavaScript evaluates as string concatenation. The dictionary now holds a string where the type promises a number.
This happens whenever the keys come from outside your program: words in a document, query-string names, usernames, or JSON field names. A user can type constructor or hasOwnProperty as easily as any other word.
`in` and `Object.hasOwn` give different answers
There are two standard ways to ask whether a key exists, and they treat inherited keys differently.
- The
inoperator checks the object and its whole prototype chain. Object.hasOwn(obj, key)checks only the object's own properties.
const lookup: Record<string, number> = { a: 1 };
console.log("toString" in lookup); // true, inherited from Object.prototype
console.log(Object.hasOwn(lookup, "toString")); // false
console.log(Object.hasOwn(lookup, "a")); // trueFor a dictionary, you almost always want own-property semantics. A key counts as present only if you put it there. Object.hasOwn was added in ES2022. To use it, your tsconfig.json needs "target": "es2022" or later, or "lib": ["es2022"] (or a newer lib). If you must support older runtimes, use the longer form:
const dict: Record<string, number> = { a: 1 };
console.log(Object.prototype.hasOwnProperty.call(dict, "a")); // true
console.log(Object.prototype.hasOwnProperty.call(dict, "toString")); // falseCalling dict.hasOwnProperty("a") directly also works on a normal object, but it fails in two cases. It fails if the dictionary has a key named hasOwnProperty, because your own value shadows the method. It also fails on a null-prototype object, covered below. Object.hasOwn avoids both problems.
A safe lookup helper
You can combine the own-property check with the index read in one small function. It returns undefined for anything that is not an own key:
function getOwn<T>(dict: Record<string, T>, key: string): T | undefined {
return Object.hasOwn(dict, key) ? dict[key] : undefined;
}
const counts: Record<string, number> = {};
for (const word of ["apple", "constructor", "apple"]) {
counts[word] = (getOwn(counts, word) ?? 0) + 1;
}
console.log(counts["apple"]); // 2
console.log(counts["constructor"]); // 1The return type T | undefined is honest. It also works the same whether or not noUncheckedIndexedAccess is on. The assignment counts["constructor"] = 1 creates an own property that shadows the inherited one, so later reads of that key behave correctly.
Null-prototype objects
A different fix is to remove the prototype link. Object.create(null) makes an object whose prototype is null. Lookups on it stop at the object itself, so there are no inherited keys.
const bare: Record<string, number> = Object.create(null);
bare["x"] = 1;
console.log("toString" in bare); // false
console.log(bare["toString"]); // undefined
console.log(Object.hasOwn(bare, "x")); // trueObject.create returns any in TypeScript, so the assignment to Record<string, number> compiles without a cast. The compiler trusts you here. Wrap the call in a small factory so the unchecked step happens in one place:
function createDict<T>(): Record<string, T> {
return Object.create(null);
}
const visits = createDict<number>();
visits["home"] = 1;
visits["constructor"] = 5;
console.log(visits["home"]); // 1
console.log(visits["constructor"]); // 5
console.log(visits["toString"]); // undefinedWith this dictionary, the original (counts[word] ?? 0) + 1 pattern works without a helper, because a missing key reads as undefined.
What you give up
A null-prototype object has none of the methods that normal objects have. Code that assumes those methods exist can fail at runtime, and the type checker does not warn you.
function createDict<T>(): Record<string, T> {
return Object.create(null);
}
const bare = createDict<number>();
bare["x"] = 1;
try {
console.log(`value: ${bare}`);
} catch (error) {
console.log(error instanceof TypeError); // true
}
console.log(Object.keys(bare)); // ["x"]
console.log(JSON.stringify(bare)); // {"x":1}Converting the object to a string throws a TypeError, because there is no toString to call. A call like bare.hasOwnProperty("x") fails for the same reason, since the method no longer exists. Functions that take an object and call these methods on it may break. Object.keys, Object.entries, JSON.stringify, and Object.hasOwn do not depend on the prototype, so they work. Logging tools may print the object with a marker such as [Object: null prototype], which is expected.
The `__proto__` key
One inherited name is special. __proto__ is an accessor on Object.prototype. Assigning to it on a normal object does not create a key. It changes the object's prototype. If your dictionary keys come from untrusted input, this matters.
function createDict<T>(): Record<string, T> {
return Object.create(null);
}
const normal: Record<string, unknown> = {};
normal["__proto__"] = { admin: true };
console.log(Object.keys(normal)); // []
console.log(normal["admin"]); // true, now inherited from the new prototype
const safe = createDict<unknown>();
safe["__proto__"] = { admin: true };
console.log(Object.keys(safe)); // ["__proto__"]
console.log(safe["admin"]); // undefinedOn the normal object, the assignment stores nothing under __proto__ and instead makes { admin: true } the object's prototype. A later read of normal["admin"] then finds true, even though no code set an admin key. This is the mechanism behind prototype-pollution bugs. On the null-prototype object, there is no __proto__ accessor to trigger, so the key is stored as plain data.
Choosing a defense
You now have three ways to deal with inherited keys. They protect against different failures.
| Approach | Stops inherited reads | Stops `__proto__` effects | Cost |
|---|---|---|---|
| `Object.hasOwn` check before each read | Yes, where you remember to use it | No, writes can still change the prototype | Every read needs the check |
| Null-prototype object | Yes, for all reads | Yes | Missing `toString` and similar methods; the type does not warn you |
| `Map` | Yes, keys never touch the prototype | Yes | A different API: `get`, `set`, `has` |
Some guidance for common cases:
- Keys you control, such as a fixed set of names in your code. A normal object is fine. The risk comes from keys you do not choose.
- Keys from input, such as words, headers, or JSON field names. Use a null-prototype object or a
Map. A later chapter coversMap. - Dictionaries returned from other people's functions. Check own properties with
Object.hasOwn. You cannot assume the object has no prototype. - Code that must serialize or pass the object to libraries. Be careful with null-prototype objects. A library that calls
obj.hasOwnProperty(...)will throw.
Whichever you choose, keep the type honest. A Record<string, number> is a claim about own keys only. Reading a key you have not checked can return something else, so combine these defenses with noUncheckedIndexedAccess from the earlier chapter.
Common mistakes
- Using
key in dictto test for presence. It returnstruefor"toString"and other inherited names. UseObject.hasOwn(dict, key). - Using
dict[key] !== undefinedas the existence test on a normal object. Inherited keys return a function, which is notundefined, so the test passes. - Using
??or||for defaults on a normal object.dict["constructor"] ?? 0returns the inherited function. - Assuming a null-prototype object has object methods. Calling
.hasOwnPropertyor.toStringon it throws. - Forgetting that spread and
Object.fromEntriesrestore the prototype. Copying a dictionary this way gives you a normal object again. - Setting
Object.hasOwnwithout checking the compile target. If TypeScript reports thathasOwndoes not exist onObjectConstructor, updatetargetorlibto ES2022 or later.
Exercise
The function below counts how often each name appears. It type-checks, but tally(["bob", "toString", "bob"]) returns a wrong value for "toString". Explain why, then rewrite the function so every count is a number. Use a null-prototype object and keep the return type Record<string, number>.
function tally(names: string[]): Record<string, number> {
const result: Record<string, number> = {};
for (const name of names) {
result[name] = (result[name] ?? 0) + 1;
}
return result;
}
Show answer
On the first "toString", result["toString"] returns the function inherited from Object.prototype. It is not undefined, so ?? 0 does not apply, and function + 1 produces a string such as "function toString() { [native code] }1". The value is a string even though the type says number. The fix is to start from an object with no prototype:
function tally(names: string[]): Record<string, number> {
const result: Record<string, number> = Object.create(null);
for (const name of names) {
result[name] = (result[name] ?? 0) + 1;
}
return result;
}
Now a missing key reads as undefined, so "toString" gets 1 on its first occurrence. An alternative is to keep the normal object and read through Object.hasOwn(result, name) ? result[name] : 0.
Exercise
What do "hasOwnProperty" in obj and Object.hasOwn(obj, "hasOwnProperty") return when const obj: Record<string, number> = {}? Then what do they return when obj is Object.create(null)?
Show answer
For {}: in returns true, because hasOwnProperty is inherited from Object.prototype, and Object.hasOwn returns false, because the object has no such own key. For Object.create(null): both return false, because there is no prototype to inherit from and no own key.