TypeScript Compiler Diagnostics
TS2532: Object is possibly undefined
With noUncheckedIndexedAccess, reading an arbitrary array position includes undefined even when the element type is number. The diagnostic points to the indexed expression rather than a named variable. Read once and check the value, preserving zero as a valid number. This does not prove that every future array access is safe. Baseline: TypeScript 5.8.3 with the shown configuration. Reproduce in one directory and create the corrected project in another. The diagnostic can have other causes; inspect its location and message before choosing a correction. Both projects keep strict checking enabled.
Formal Syntax & Structure
typescript syntaxtypescript
TS2532 (compiler diagnostic code, not TypeScript syntax)Working Example
Example Snippettypescript
// INTENTIONALLY INVALID — reproduce// File: tsconfig.json (omit this label){ "compilerOptions": { "strict": true, "target": "ES2022", "module": "CommonJS", "types": [], "lib": [ "ES2022", "DOM" ], "noEmitOnError": true, "outDir": "dist", "noUncheckedIndexedAccess": true }, "files": [ "main.ts" ]}
// File: main.ts (omit this label)function first(values: number[]) { return values[0].toFixed(1); }
// Run: tsc -p . --pretty false// Expected: TS2532; no output emitted.
// CORRECTED PROJECT — separate directory// File: tsconfig.json (omit this label){ "compilerOptions": { "strict": true, "target": "ES2022", "module": "CommonJS", "types": [], "lib": [ "ES2022", "DOM" ], "noEmitOnError": true, "outDir": "dist", "noUncheckedIndexedAccess": true }, "files": [ "main.ts" ]}
// File: main.ts (omit this label)function first(values: number[]) { const n = values[0]; return n === undefined ? "missing" : n.toFixed(1); }console.log(first([0]), first([]));
// Run: tsc -p . --pretty false// Expected: no diagnostics.// Run: node dist/main.js// Expected stdout: 0.0 missing