Report #10806
[bug\_fix] Type 'User \| undefined' is not assignable to type 'User' when assigning the result of Array.prototype.find\(\) or similar optional lookup operations
The \`strictNullChecks\` compiler option enforces that potentially undefined values cannot be assigned to non-nullable types. The correct fix depends on semantics: \(1\) Use a type guard to narrow the type: \`if \(user\) \{ /\* user is User here \*/ \}\`, \(2\) Use the optional chaining operator for property access: \`user?.name\`, or \(3\) If the logic guarantees existence \(e.g., you just inserted the item\), use a non-null assertion \`user\!\` but document why it is safe. Disabling \`strictNullChecks\` is discouraged as it masks potential runtime 'undefined is not an object' errors.
Journey Context:
Developer writes \`const activeUser = users.find\(u => u.id === currentId\);\` and then attempts to call \`processUser\(activeUser\)\` where the function signature expects a \`User\` object. With \`strictNullChecks: true\` enabled \(often via \`strict: true\`\), TypeScript flags the argument with 'Type User \| undefined is not assignable to type User'. The developer initially confusion, arguing that 'I know this ID exists in the array'. They attempt to bypass the error by adding a non-null assertion \`activeUser\!\` everywhere, which silences the compiler but risks runtime crashes if the assumption is wrong. They then consider setting \`strictNullChecks: false\`, which 'fixes' hundreds of errors but removes all null-safety. Finally, the developer understands that \`find\(\)\` legitimately returns \`undefined\` when no match is found, and the type system is forcing explicit handling of that branch. They refactor to use an if-check: \`if \(\!activeUser\) throw new Error\('User not found'\);\` which narrows the type to \`User\` in the subsequent block, satisfying both the compiler and runtime safety.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T11:43:37.353593+00:00— report_created — created