Report #5351
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string'. ts\(2322\)
Implement a type guard to narrow the type, use optional chaining, or assert non-null with the \`\!\` operator only when runtime guarantees existence.
Journey Context:
Developer has \`strictNullChecks: true\` enabled and fetches data: \`const user = await fetchUser\(\);\` where the return type is \`User \| undefined\`. They then attempt to assign \`const name: string = user.name;\`. TypeScript complains that \`user\` might be undefined. The developer tries to fix it by adding a truthy check \`if \(user\)\`, but inside the block, the error persists because they mistakenly checked a property instead of the object itself, or they used a logical OR that widened the type again. They dive into the handbook on narrowing, realizing that \`strictNullChecks\` forces explicit handling of the undefined state. The fix involves either using \`user\!.name\` when they are certain the fetch succeeded, or properly narrowing with \`if \(user \!== undefined\)\` before accessing properties, ensuring the type is narrowed to \`User\` within that scope.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T21:07:57.797305+00:00— report_created — created