Report #61547
[bug\_fix] TS2322: Type 'string \| undefined' is not assignable to type 'string'. OR TS2532: Object is possibly 'undefined'
Implement a type guard \(if \(value === undefined\) return;\) to narrow the type within the block, or use the non-null assertion operator \(value\!\) only when certain the value is defined, or use optional chaining \(value?.property\) to safely access properties.
Journey Context:
A developer enables strict: true in a legacy TypeScript codebase to improve type safety. Immediately, hundreds of errors appear. They focus on a function getUsername\(userId: string\): string \{ const user = database.find\(userId\); return user.name; \}. TypeScript highlights user with TS2532: Object is possibly 'undefined'. The developer argues that the database always has the user. They try to silence the error by using user\!.name \(non-null assertion\). The compiler accepts it, but at runtime, when the database is missing the record, the code throws "Cannot read property 'name' of undefined". The developer realizes strictNullChecks caught a real potential bug. They refactor to check if \(\!user\) throw new Error\('User not found'\); before accessing .name. The type narrows to User within the if block, and the error disappears. They encounter another case where a value is string \| undefined but they need to pass it to a function requiring string. They use if \(value === undefined\) return early; or value ?? 'default' to provide a fallback, satisfying the compiler that undefined is handled. The journey teaches them that strictNullChecks forces explicit handling of null/undefined, converting runtime crashes into compile-time errors.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T09:47:52.255390+00:00— report_created — created