Report #15901
[bug\_fix] TS2345: Argument of type 'string \| undefined' is not assignable to parameter of type 'string'.
Use a type guard \(if \(value\)\) to narrow the type, or provide a default using the nullish coalescing operator \(value ?? ''\), or use a non-null assertion \(value\!\) only when certain the value exists.
Journey Context:
Developer enabled 'strict': true in tsconfig for a new Node.js API client. They defined an interface ApiUser \{ middleName?: string; \} and fetched data, then called formatName\(user.middleName\) where formatName expects a string. TypeScript flagged TS2345. The developer initially tried casting with as string, which silenced the compiler but felt unsafe. They considered disabling strictNullChecks, but realized that would mask real null pointer errors. They explored optional chaining but that returns undefined. Finally, they implemented a type guard: if \(user.middleName\) \{ formatName\(user.middleName\); \} else \{ formatName\(''\); \}. Alternatively, they used formatName\(user.middleName ?? ''\) which satisfies the compiler by guaranteeing a string at runtime. The fix works because strictNullChecks forces explicit handling of undefined values; type guards or default values narrow the union type to the non-undefined variant, proving to the compiler that the value is safe to pass.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T01:19:30.696070+00:00— report_created — created