Sub topic 2
Handling Missing Keys in TypeScript Dictionaries
Assume you know basic TypeScript types, interfaces, unions, and JavaScript object property access. This chapter focuses on dictionary objects whose keys are not known in advance.
`noUncheckedIndexedAccess`
An index signature describes the type of values stored under arbitrary keys:
const ages: Record<string, number> = {
ann: 30,
};
const age = ages["bob"];Without extra checking, TypeScript treats age as a number, even though "bob" is not present at runtime. Enable noUncheckedIndexedAccess to model this possibility:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true
}
}Now ages["bob"] has type number | undefined. Check the result before using it:
const age = ages["ann"];
if (age !== undefined) {
console.log(age.toFixed(0));
} else {
console.log("Age is not recorded");
}Checking That a Key Exists
Use Object.hasOwn when the key must belong directly to the dictionary:
const scores: Record<string, number> = { alice: 90 };
const name = "alice";
if (Object.hasOwn(scores, name)) {
const score = scores[name];
console.log(score);
}Object.hasOwn narrows the access in current TypeScript libraries and excludes inherited properties. The in operator also checks inherited properties:
console.log("toString" in scores); // true
console.log(Object.hasOwn(scores, "toString")); // falseInherited Keys and Null-Prototype Objects
Normal objects inherit properties from Object.prototype. A dictionary lookup for "toString" can therefore collide with an inherited property. For untrusted or arbitrary keys, create a null-prototype object:
const dictionary: Record<string, number> = Object.create(null);
dictionary["count"] = 1;
console.log("toString" in dictionary); // false
console.log(Object.hasOwn(dictionary, "count")); // trueExercise
Why should Object.hasOwn(dictionary, key) usually be preferred over key in dictionary for a dictionary object?
Show answer
Object.hasOwn checks only keys stored directly on the dictionary, while in also finds inherited properties such as toString.