Sub topic 6
Checking That a Key Exists
Assume you know basic TypeScript types, interfaces, type aliases, union types, and JavaScript object property access. This chapter focuses on checking whether a dictionary object contains a key before using its value.
A dictionary is an object whose keys are not all known when you write the code. An index signature describes the value type for those keys:
interface UserScores {
[username: string]: number;
}
const scores: UserScores = {
alice: 90,
bob: 85,
};A lookup may refer to a key that is missing:
const score = scores["carol"];At runtime, score is undefined. TypeScript can model this possibility when noUncheckedIndexedAccess is enabled.
Checking with `Object.hasOwn`
Object.hasOwn(object, key) returns true when the key is an own property of the object. An own property is stored directly on that object, rather than inherited from its prototype.
const scores: Record<string, number> = {
alice: 90,
};
const username = "alice";
if (Object.hasOwn(scores, username)) {
console.log(scores[username].toFixed(0));
}This check is useful when a key must be explicitly present in the dictionary. It does not count inherited properties.
With modern TypeScript libraries, Object.hasOwn also helps TypeScript narrow the value after the check. If your project targets an older JavaScript library, configure lib for ES2022 or later, or use another supported own-property check.
Checking with the `in` operator
The in operator checks whether a property exists anywhere in the object's property chain. That includes properties inherited from the prototype.
const scores: Record<string, number> = {
alice: 90,
};
console.log("alice" in scores); // true
console.log("toString" in scores); // true
console.log("carol" in scores); // falseThe "toString" result is true because ordinary objects inherit toString from Object.prototype. Therefore, use in when inherited properties should count. Use Object.hasOwn when you want only keys stored in the dictionary itself.
| Check | Own properties | Inherited properties | Typical use |
|---|---|---|---|
| `Object.hasOwn(obj, key)` | Yes | No | Dictionary membership |
| `key in obj` | Yes | Yes | Any accessible property |
A safe lookup pattern
A check and a lookup work well together:
interface Prices {
[productId: string]: number;
}
const prices: Prices = {
book: 12.5,
pen: 1.25,
};
function getPrice(prices: Prices, productId: string): number | undefined {
if (Object.hasOwn(prices, productId)) {
return prices[productId];
}
return undefined;
}
const price = getPrice(prices, "book");
if (price !== undefined) {
console.log(`Price: $${price.toFixed(2)}`);
}The function returns number | undefined because a requested product might not exist. The caller must check the result before calling a number method.
When noUncheckedIndexedAccess is enabled, direct indexed access also reflects this uncertainty:
// tsconfig.json
// {
// "compilerOptions": {
// "strict": true,
// "noUncheckedIndexedAccess": true
// }
// }
const prices: Record<string, number> = {
book: 12.5,
};
const price = prices["missing"]; // number | undefined
if (price !== undefined) {
console.log(price.toFixed(2));
}This setting catches assumptions that every possible key has a value.
Choosing the check
Use Object.hasOwn for configuration tables, caches, and dictionaries where only explicitly stored keys are valid. Use in when inherited properties are intentionally part of the lookup behavior, such as when working with class instances or prototype-based objects.
For a plain object used as a dictionary, Object.hasOwn is usually the safer default because it avoids treating prototype properties as dictionary entries.
Exercise
What is the difference between Object.hasOwn(dictionary, key) and key in dictionary?
Show answer
Object.hasOwn checks only properties stored directly on dictionary. The in operator also returns true for properties inherited through the prototype chain.