Sub topic 6
Checking that a key exists
This chapter assumes you know how to declare an index signature such as Record<string, number>. It also assumes you know what noUncheckedIndexedAccess does, and that you are comfortable with undefined in union types. Here you will learn the three ways to ask "is this key in the dictionary?", and what each one answers.
Two different questions
Code that works with a dictionary asks one of two questions:
- Does the value for this key exist, and is it usable?
- Does this key exist on the object at all?
These sound the same, but they can have different answers. An object can hold a key whose value is undefined. An object can also report a key that you never put there, because it came from the prototype. The type system helps with the first question. It cannot help with the second.
An index signature tells TypeScript only that any string key may be read and will produce a number. It does not list which keys are present. So scores["zoe"] is accepted at compile time even when no zoe entry exists. Runtime checks fill that gap.
Checking the value
The most common check reads the value and tests it. With noUncheckedIndexedAccess turned on, the type is number | undefined, and TypeScript makes you narrow it before use:
// tsconfig.json: { "compilerOptions": { "noUncheckedIndexedAccess": true } }
const ages: Record<string, number> = { ann: 30 };
const age = ages["ann"]; // number | undefined
if (age !== undefined) {
console.log(age.toFixed(0));
}Copy the lookup into a const first, as above. TypeScript narrows a const variable reliably. Repeated lookups such as ages[name] are narrowed only in limited cases. This works when the key is a literal or a const identifier. It does not work when the key is a changing expression.
Do not use a truthiness test
Writing if (scores[name]) is a common shortcut, and it has a bug. Falsy values are treated as missing:
const scores: Record<string, number> = { alice: 0, bob: 85 };
if (scores["alice"]) {
console.log("found alice");
} else {
console.log("alice missing?"); // prints, even though alice is stored with 0
}Use !== undefined, or the nullish coalescing operator ?? when you want a default. ?? replaces only null and undefined, and leaves 0, "" and false alone:
const scores: Record<string, number> = { alice: 0, bob: 85 };
const alice = scores["alice"] ?? -1;
console.log(alice); // 0Where the value check falls short
A value check reports "usable value present". It cannot tell these cases apart:
- The key is absent.
- The key is present and its value is
undefined.
For most dictionaries both mean "nothing here", and the value check is enough. It stops being enough in two situations. One is when undefined is a meaningful stored value. The other is when the key may be inherited, which the next sections cover.
The `in` operator
The in operator tests the key itself, not the value:
const flags: Record<string, boolean | undefined> = { debug: undefined };
console.log(flags["debug"] !== undefined); // false
console.log("debug" in flags); // true
console.log("verbose" in flags); // falseHere in and the value check disagree. debug is a real key whose value is undefined. Use in when presence matters regardless of the value, for example "was this option supplied explicitly?".
in has one behavior that surprises people. It walks the prototype chain, so it finds inherited properties as well as the object's own:
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")); // truetoString was never added to lookup, yet in reports it. If a user supplies the key "constructor" or "toString", an in check wrongly says the entry exists. The value read then returns a function, and TypeScript still believes it is a number. The type Record<string, number> is simply wrong for those keys. The chapter on inherited keys covers this in detail. For now, remember that in is the wrong tool for plain-object dictionaries keyed by untrusted strings.
in also converts its left operand to a property key. 1 in obj checks for the string key "1". That fits number index signatures, which are stored as string keys at runtime anyway.
`Object.hasOwn`
Object.hasOwn(obj, key) returns true only when key is an own property of obj. It ignores the prototype chain, so inherited names such as toString give false. It is the right default for "does this dictionary contain this key".
It requires ES2022. If TypeScript reports Property 'hasOwn' does not exist on type 'ObjectConstructor', set "lib": ["es2022"] or later, or set "target": "es2022", in tsconfig.json. Your runtime must support it too. That means Node 16.9 or later and current browsers.
On older runtimes, the classic equivalent is:
const lookup: Record<string, number> = { a: 1 };
const has = Object.prototype.hasOwnProperty.call(lookup, "a");
console.log(has); // trueDo not write lookup.hasOwnProperty("a"). It breaks when the dictionary has its own key named hasOwnProperty, or when the object has a null prototype and no such method.
Narrowing does not follow `hasOwn`
Object.hasOwn returns a plain boolean. It does not narrow the result of a later index read:
const prices: Record<string, number> = { apple: 3 };
const item = "apple";
if (Object.hasOwn(prices, item)) {
const p = prices[item]; // number, or number | undefined with noUncheckedIndexedAccess
console.log(p);
}With noUncheckedIndexedAccess on, p is still number | undefined inside the if. TypeScript does not connect the check to the read. You have two honest options. One is to read first and test the value. The other is to wrap the pair in a helper and be explicit about the result:
function getOwn<T>(dict: Record<string, T>, key: string): T | undefined {
return Object.hasOwn(dict, key) ? dict[key] : undefined;
}
const prices: Record<string, number> = { apple: 3 };
const apple = getOwn(prices, "apple"); // number | undefined
const toString = getOwn(prices, "toString"); // undefined, as it should be
if (apple !== undefined) {
console.log(apple + 1); // 4
}The helper gives one function that answers "own key with a value, or undefined". Its return type is honest, so callers do not need to remember the prototype rules. Note that with noUncheckedIndexedAccess on, the expression dict[key] already has type T | undefined, which matches the declared return type. With the flag off it is T, which also fits.
Choosing a check
| Check | Question it answers | Sees inherited keys? | Key present with value `undefined` |
|---|---|---|---|
| `dict[k] !== undefined` | Is there a usable value? | Yes, and the type is then wrong | `false` |
| `k in dict` | Is the key on the object or its prototype chain? | Yes | `true` |
| `Object.hasOwn(dict, k)` | Is the key an own property? | No | `true` |
| `getOwn(dict, k) !== undefined` | Is there an own, usable value? | No | `false` |
Edge cases to know
- Arrays and number keys.
2 in arrtests for an index, not a value. A sparse array such as[1, , 3]reports1 in arrasfalse. With a number index signature, the same rule applies:inandhasOwncheck the string form of the key. - Symbol keys.
inandObject.hasOwnboth accept symbols, so they work on dictionaries keyed bysymbol. - Deleting keys. After
delete dict[k], bothinandObject.hasOwnreturnfalse. Assigningdict[k] = undefinedleaves the key present, and only the value check treats it as missing. Pick one convention for "remove an entry" and use it everywhere. - Optional properties are different. For a type such as
{ a?: number }, theinoperator does narrow the type, because the property is a known name. Narrowing byinworks on known property names in unions, not on arbitrary keys of an index signature. Mapavoids the whole problem.map.has(key)checks only the map's own entries, andmap.get(key)always returnsT | undefined. A later chapter covers when to choose it.
A complete example
This program counts words and reports whether a word was seen. It uses Object.hasOwn for presence, a ?? default for counting, and a separate check for the "key present but zero" case. Compile with target set to es2022.
const counts: Record<string, number> = {};
function add(word: string): void {
counts[word] = (Object.hasOwn(counts, word) ? counts[word] ?? 0 : 0) + 1;
}
function report(word: string): string {
if (!Object.hasOwn(counts, word)) {
return `${word}: never seen`;
}
return `${word}: ${counts[word] ?? 0}`;
}
for (const w of ["apple", "pear", "apple", "constructor"]) {
add(w);
}
console.log(report("apple")); // apple: 2
console.log(report("constructor")); // constructor: 1
console.log(report("toString")); // toString: never seenThe word constructor is counted correctly. A version that used counts[word] ?? 0 without the own-key check would read the inherited Object constructor function for that word and produce a nonsense total. The ?? 0 after counts[word] is there only to satisfy noUncheckedIndexedAccess. The hasOwn check has already established that the value exists.
Summary of the working model
- A value check (
!== undefined) is the default for ordinary lookups. Never use truthiness for values that may be0,""orfalse. - Use
inonly when you want inherited keys included, or when your object has a known shape. - Use
Object.hasOwnfor dictionary keys, especially when they come from input you do not control. - TypeScript does not link a
hasOwncheck to a later read. Re-check the value, or use a small helper likegetOwn.
Exercise
Given const flags: Record<string, boolean | undefined> = { debug: undefined };, what do flags["debug"] !== undefined, "debug" in flags and Object.hasOwn(flags, "debug") return, and which would you use to find out whether the caller explicitly set debug?
Show answer
They return false, true and true. The value check cannot see a key that is stored with the value undefined. To detect an explicit setting, use Object.hasOwn(flags, "debug"), because it tests only own keys and does not pick up inherited ones. in also returns true here, but it would also report inherited names.
Exercise
A dictionary const stock: Record<string, number> = { widget: 0 }; is checked with if (stock[item]) { ... } else { console.log("not stocked"); }. What goes wrong for item = "widget", and how do you fix it so that unknown items such as "toString" are also handled correctly?
Show answer
The stored value 0 is falsy, so the code prints "not stocked" for an item that is stocked with quantity zero. Replace the truthiness test with an own-key check followed by a value read, for example if (Object.hasOwn(stock, item)) { const qty = stock[item] ?? 0; ... } else { console.log("not stocked"); }. This keeps widget (quantity 0) as stocked, and treats "toString" as not stocked because it is inherited, not an own key.