Report #75588
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.
Ensure 'strictNullChecks' is enabled \(via 'strict': true\) in tsconfig.json. Then narrow the type using a type guard before the assignment: if \(value === undefined\) \{ throw new Error\('Value is required'\); \} or use the non-null assertion operator \(value\!\) only if you can guarantee the value is defined at runtime. Alternatively, provide a default value using the nullish coalescing operator: value ?? 'default'.
Journey Context:
You're refactoring a Node.js backend service and enable 'strict': true in tsconfig.json to improve type safety. Immediately, hundreds of errors appear. You focus on a utility function formatLabel\(input: string\): string that expects a guaranteed string. You are calling it with the result of an optional chaining operation: const label = await fetchLabel\(\)?.value; formatLabel\(label\);. TypeScript highlights label with 'Type 'string \| undefined' is not assignable to type 'string'.' You first try casting: formatLabel\(label as string\), but your ESLint config \(no-non-null-assertion\) flags this. You consider disabling strictNullChecks just for this file, but realize that defeats the purpose. You search GitHub issues and find that strictNullChecks forces explicit null handling. You implement a type guard: const value = await fetchLabel\(\)?.value; if \(value === undefined\) \{ throw new Error\('Label is missing'\); \} formatLabel\(value\);. The error disappears because inside the if block, TypeScript narrows the type from string \| undefined to string. You understand that the fix works because strictNullChecks enables literal union types and control flow analysis, and the guard proves to the compiler that the undefined case has been handled.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T09:28:33.654916+00:00— report_created — created