Report #88012
[bug\_fix] TS2322: Type 'string \| undefined' is not assignable to type 'string'. OR TS2532: Object is possibly 'undefined'.
Enable 'strictNullChecks': true \(usually via 'strict': true\). The error indicates a value could be undefined/null but is being used where a definite value is required. Fix by adding a type guard: 'if \(x \!== undefined\) \{ ... \}', using optional chaining 'x?.property', providing a default value 'x ?? defaultVal', or using a non-null assertion 'x\!' \(unsafe, avoid if possible\). For class properties, ensure initialization in constructor or use definite assignment assertion 'prop\!: Type'.
Journey Context:
Developer enables 'strict': true in an existing JavaScript codebase to improve type safety. Immediately faces thousands of errors. Focusing on one: 'function greet\(name: string\) \{ console.log\(name.toUpperCase\(\)\); \}' called with 'const username = localStorage.getItem\('user'\); greet\(username\);'. TypeScript reports 'TS2345: Argument of type 'string \| null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.' Developer initially tries casting: 'greet\(username as string\)' which silences the error but is unsafe. Realizes 'localStorage.getItem' returns null if key missing. Implements a check: 'if \(username\) \{ greet\(username\); \} else \{ greet\('Guest'\); \}'. TypeScript now accepts this because inside the 'if' block, 'username' is narrowed from 'string \| null' to 'string'. Later encounters 'Object is possibly 'undefined'' when accessing 'user.profile.name' where 'profile' is optional. Learns about optional chaining: 'user.profile?.name' which returns undefined if profile missing, safely. Understands that strictNullChecks forces handling of edge cases where values might be absent, preventing runtime 'null is not an object' errors at the cost of more verbose null-checking code.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T06:18:45.806112+00:00— report_created — created