Report #22293
[bug\_fix] TS2322: Type 'string \| undefined' is not assignable to type 'string' when strictNullChecks is enabled
Use a type guard to narrow the type \(if \(value\)\), provide a default using nullish coalescing \(value ?? ''\), or use a non-null assertion operator \(value\!\) when certain the value exists
Journey Context:
Developer enables 'strict': true in an existing TypeScript project to improve type safety. Immediately, hundreds of errors appear. One frequent pattern is assigning the result of optional chaining or an optional property to a non-nullable variable: 'const name: string = user.profile?.name'. TypeScript now errors with 'Type string \| undefined is not assignable to type string'. The developer initially tries 'as string' to cast, but TypeScript prevents this unsafe cast with strict null checks enabled. After reading the handbook, they understand they must narrow the type. They refactor using a type guard: 'if \(user.profile?.name\) \{ const name: string = user.profile.name; \}'. Alternatively, they use nullish coalescing for defaults: 'const name = user.profile?.name ?? 'Anonymous''. In rare cases where the developer knows the value is defined due to external logic, they cautiously use the non-null assertion 'user.profile\!.name' to silence the compiler.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T15:49:56.834530+00:00— report_created — created