Sub topic 12
noUncheckedIndexedAccess and exactOptionalPropertyTypes
This chapter assumes you have strictNullChecks enabled and you are comfortable with unions, narrowing, ?., ??, and optional properties. It covers two compiler options that "strict": true does not turn on. Each closes a gap that strictNullChecks leaves open.
Two gaps in strictNullChecks
With strictNullChecks, the compiler tracks null and undefined in declared types. It still trusts two things that are not always true:
- Indexing.
names[5]is typed asstringeven when the array has two items. - Optional properties.
{ theme?: string }accepts{ theme: undefined }, even though "absent" and "present but undefined" behave differently at runtime.
| Option | Gap it closes | Added in | Part of `strict`? |
|---|---|---|---|
| `noUncheckedIndexedAccess` | Index reads are assumed to succeed | TypeScript 4.1 | No |
| `exactOptionalPropertyTypes` | `?` allows an explicit `undefined` | TypeScript 4.4 | No |
Both require strictNullChecks. exactOptionalPropertyTypes has no effect without it, because there is no undefined to be strict about.
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
}
}noUncheckedIndexedAccess
What it changes
When the flag is on, reading through an index signature or an array index adds undefined to the result type. The compiler cannot know whether the index is in range, so it makes you handle that case.
const names: string[] = ["Ada", "Grace"];
const first = names[0]; // string | undefined with the flag on
// first.toUpperCase(); // Error: 'first' is possibly 'undefined'.
if (first !== undefined) {
console.log(first.toUpperCase());
}Without the flag, first is string, and names[10].toUpperCase() compiles and then throws at runtime.
The same rule applies to objects with index signatures, including Record<string, T>:
const stock: Record<string, number> = { apples: 3 };
const pears = stock["pears"]; // number | undefined
const count = stock.pears ?? 0;
console.log(count); // 0What it does not change
The flag only affects reads that go through an index signature or an array or tuple index. Several common patterns are unchanged.
| Code | Type with the flag on | Why | Column |
|---|---|---|---|
| `arr[0]` on `string[]` | `string \ | undefined` | Index access on an array |
| `for (const x of arr)` | `string` | The iterator only yields existing items | |
| `arr.map(x => ...)` | `x` is `string` | Callbacks receive existing items | |
| `arr.at(0)` | `string \ | undefined` | Already included `undefined` |
| `tuple[0]` on `[number, string]` | `number` | The tuple length is known | |
| `obj.name` on `{ name: string }` | `string` | A declared property, not an index signature |
Writes are not affected. names[5] = "x" is still checked against string.
Handling the new undefined
Four approaches cover most cases.
- Narrow with a check. This is the right choice when the missing case needs a real response.
- Give a default with
??. This works when a fallback is meaningful. - Iterate instead of indexing. Use
for...of,map, orforEachso you never index at all. - Assert with
!. Use it only when an invariant outside the type system guarantees the index is valid.
Index loops are the most common source of new errors:
const values: number[] = [4, 8, 15];
// With the flag on, values[i] is number | undefined.
let total = 0;
for (let i = 0; i < values.length; i++) {
const v = values[i];
if (v !== undefined) {
total += v;
}
}
// Usually clearer:
let total2 = 0;
for (const v of values) {
total2 += v;
}
console.log(total, total2); // 27 27Copy the indexed value into a const before narrowing it. Narrowing values[i] directly does not reliably carry over to later uses when the index is a variable.
Tradeoffs
The flag is the more disruptive of the two options, and some teams turn it off on purpose.
- Loops written with
for (let i...)produce many errors. Most are real in the sense that an index could be out of range, but in a bounded loop they are noise. - Destructuring becomes noisier.
const [head] = namesgivesstring | undefined. - Code that has already checked
arr.lengthgets no credit for that check.
The benefit is in code that reads by a computed or user-supplied key, such as lookup tables, parsed CSV rows, and Record caches. In those places an absent key is routine, and the unflagged type hides it.
exactOptionalPropertyTypes
What it changes
By default, theme?: string means theme?: string | undefined. The type permits two different shapes: the property is missing, or the property exists with the value undefined. With the flag on, ? means only "may be missing". If the property is present, its value must match the declared type.
interface Settings {
theme?: string;
}
const a: Settings = {};
const b: Settings = { theme: "dark" };
// const c: Settings = { theme: undefined };
// Error: Type 'undefined' is not assignable to type 'string'
// with 'exactOptionalPropertyTypes: true'.
// Consider adding 'undefined' to the type of the target.Reading is not affected. settings.theme is still string | undefined, because the property may be missing.
Why the difference matters
The two shapes behave differently in several places:
"theme" in settingsistruefor{ theme: undefined }andfalsefor{}.Object.keysandObject.entrieslist a property that is present with the valueundefined.JSON.stringifydrops properties whose value isundefined, so the two shapes serialize the same way. Spreading keeps them different:{ ...defaults, ...overrides }overwrites a default withundefinedifoverrideshas an explicittheme: undefined, but leaves it alone if the key is absent.
That last case causes real bugs. A merge of user options over defaults can silently erase a default:
interface Options {
retries?: number;
}
const defaults = { retries: 3 };
const overrides: { retries?: number | undefined } = { retries: undefined };
const merged = { ...defaults, ...overrides };
console.log(merged.retries); // undefined, not 3With the flag on and Options as declared above, { retries: undefined } would not type-check as an Options value, so the problem is caught where the value is built.
Opting back in to undefined
When undefined is a legitimate value, say so in the type:
interface LooseSettings {
theme?: string | undefined;
}
const c: LooseSettings = { theme: undefined }; // allowedThis is also how you model a patch, where three states mean three different things: absent means "leave unchanged", null means "clear", and a value means "set".
interface ProfilePatch {
nickname?: string | null;
}
function applyPatch(current: { nickname: string | null }, patch: ProfilePatch) {
return {
nickname: "nickname" in patch ? (patch.nickname ?? null) : current.nickname,
};
}
console.log(applyPatch({ nickname: "Ace" }, {})); // { nickname: 'Ace' }
console.log(applyPatch({ nickname: "Ace" }, { nickname: null })); // { nickname: null }
console.log(applyPatch({ nickname: "Ace" }, { nickname: "Bo" })); // { nickname: 'Bo' }Building objects from optional parameters
Function parameters are not affected by the flag. A parameter theme?: string has the type string | undefined, so passing it straight into an optional property now fails. Build the object conditionally:
interface Settings {
theme?: string;
}
function makeSettings(theme?: string): Settings {
return theme === undefined ? {} : { theme };
}
console.log(makeSettings()); // {}
console.log(makeSettings("dark")); // { theme: 'dark' }Writing return { theme } here is an error, because theme may be undefined.
You can remove an optional property with delete settings.theme. Setting it to undefined is the error.
Tradeoffs and library friction
- Type definitions. Some libraries declare
foo?: stringand then accept or return{ foo: undefined }. Passing such values into your own code fails the check. You often have to widen types at the boundary. - Mapped types.
Partial<T>makes properties optional with?. Under the flag,Partial<{ a: number }>does not accept{ a: undefined }. This surprises people who build update objects from possibly undefined variables. - Readability.
?: T | undefinedlooks redundant to readers who have not seen the flag. Add a comment where it is deliberate.
Choosing what to enable
A practical order for an existing project:
- Finish the
strictNullChecksmigration first. The two options produce errors that are easy to confuse with unfinished migration work. - Turn on
noUncheckedIndexedAccessnext. Fix loops by switching tofor...ofwhere you can, and keep!for the few cases with a proven invariant. - Turn on
exactOptionalPropertyTypeslast, and expect most of the errors to appear at the boundaries with third-party types and serialized data.
Each option can be enabled alone in its own commit, so a regression is easy to trace to one change.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `'x' is possibly 'undefined'` after indexing | `noUncheckedIndexedAccess` is on | Copy to a `const`, then narrow or use `??` | |
| `Type 'undefined' is not assignable to type 'string' with 'exactOptionalPropertyTypes: true'` | An explicit `undefined` assigned to a `?` property | Omit the key, or declare `?: string \ | undefined` |
| No new errors after enabling `exactOptionalPropertyTypes` | `strictNullChecks` is off | Enable `strictNullChecks` | |
| `for (let i...)` loop fills with errors | Index reads now include `undefined` | Use `for...of`, or narrow a local `const` |
Exercise
With both options enabled, what are the types of a and b in the code below, and does the assignment to config compile?
const items: string[] = ["x"];
const a = items[0];
interface Config { mode?: string }
const mode: string | undefined = process.env.MODE;
const config: Config = { mode };
const b = config.mode;
Show answer
a is string | undefined because noUncheckedIndexedAccess adds undefined to array index reads. The assignment { mode } does not compile, because mode may be undefined and exactOptionalPropertyTypes forbids assigning undefined to mode?: string. Fix it with mode === undefined ? {} : { mode }, or declare mode?: string | undefined. Reading is unchanged, so b is string | undefined.
Exercise
Why does for (const item of items) produce no new errors under noUncheckedIndexedAccess, while for (let i = 0; i < items.length; i++) { items[i] } does?
Show answer
The for...of loop uses the array's iterator, which yields only existing elements, so each item has the element type. The indexed loop reads items[i] through an index, and the compiler cannot prove i is in range, so the result type includes undefined.