Report #6525
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string' with strictNullChecks enabled
Use a type guard \(e.g., \`if \(user\)\` or \`if \(user \!== undefined\)\`\) to narrow the type within the block, or use the nullish coalescing operator \(\`??\`\) to provide a default value. Root cause: strictNullChecks treats undefined and null as distinct types; assignability requires explicit narrowing or null-checking to prove to the compiler that the value is defined at that point.
Journey Context:
Developer fetches a user record from a database function returning \`Promise\`. They assign the result to \`const user = await getUser\(id\)\`. In the next line, they attempt \`const name: string = user.name\`, triggering the error. The developer first tries casting: \`\(user as User\).name\`, which compiles but feels unsafe. They then add a check \`if \(user\) \{ const name = user.name; \}\` and the error disappears. Investigating further, they learn that TypeScript's control flow analysis narrows the type within the truthy block, proving \`user\` is no longer null. They refactor to use optional chaining with nullish coalescing: \`const name = user?.name ?? 'Anonymous'\`, which satisfies the compiler by guaranteeing a string.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T00:17:22.771683+00:00— report_created — created