Report #60988
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string' with strictNullChecks \(TS2322\)
Implement a type guard to narrow the type: \`if \(\!user\) throw new Error\('Not found'\);\` or use the non-null assertion operator \`user\!.name\` only if certain the value exists. The root cause is that \`Array.prototype.find\(\)\` returns \`T \| undefined\`, and \`strictNullChecks\` enforces explicit handling of the undefined case before accessing properties.
Journey Context:
You enabled \`strict: true\` in \`tsconfig.json\` for a React project to catch potential null errors. You have an array \`const users = \[\{id: 1, name: 'Alice'\}, \{id: 2, name: 'Bob'\}\]\` and you write \`const user = users.find\(u => u.id === 1\); console.log\(user.name.toUpperCase\(\)\);\`. TypeScript immediately flags \`user.name\` with 'Object is possibly undefined'. Hovering reveals the type is \`\{id: number, name: string\} \| undefined\`. You initially try to cast it with \`as \{id: number, name: string\}\` but realize this disables type safety. You consider disabling \`strictNullChecks\` but remember this catches real bugs. You add an explicit check: \`if \(\!user\) return null;\` before accessing \`user.name\`. After this check, TypeScript's control flow analysis narrows the type to exclude \`undefined\` within the subsequent code block, and the error disappears. You realize TypeScript performed type narrowing based on the explicit guard.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T08:51:30.083050+00:00— report_created — created