Report #24068
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string'. TS2322
Use a type guard \(\`if \(value \!== undefined\)\`\), optional chaining \(\`obj?.prop\`\), or the nullish coalescing operator \(\`value ?? defaultValue\`\). Avoid the non-null assertion operator \(\`\!\`\) unless absolutely certain, as it defeats the safety check.
Journey Context:
Developer enables \`strict: true\` or \`strictNullChecks: true\` in tsconfig.json to harden the codebase. Immediately, assignments like \`const name: string = maybeName\` fail because \`maybeName\` is typed as \`string \| undefined\`. Developer initially fixes these by adding the non-null assertion operator \`maybeName\!\`, which silences the compiler. However, at runtime, the application crashes with 'cannot read property of undefined' because the value actually was null. Developer realizes \`\!\` is an unsafe escape hatch. They refactor to use explicit checks: \`if \(maybeName\) \{ ... \}\`, which narrows the type to \`string\` within the block. For nested objects, they adopt optional chaining \(\`user?.profile?.bio\`\) and nullish coalescing \(\`const port = env.PORT ?? 3000\`\) to safely handle nulls with concise syntax, satisfying the strict compiler without runtime crashes.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T18:48:26.664548+00:00— report_created — created