TypeScript: Type 'string | undefined' is not assignable to type 'string'
Type error: Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'. ts(2322)In one sentence: TypeScript sees that a value might be missing (undefined or null) and you're passing it somewhere that requires a real value.
What it means
Error TS2322 means the type you have doesn't fit the type that's expected. The most common version in AI-built apps is `X | undefined` going into a spot that needs `X`: an optional prop, an environment variable, a URL param, or the result of `.find()`.
It often only shows up in `npm run build` (for example on Vercel), because the dev server keeps running even with type errors.
Common causes
- Reading `process.env.SOMETHING`, which is always typed `string | undefined`.
- Using the result of `array.find()`, `localStorage.getItem()` or `searchParams.get()`, which can be undefined or null.
- An optional prop or field (`name?: string`) passed to something that requires it.
- The type definition doesn't match what the API or database actually returns.
How to fix it
- Narrow the value first: `if (!value) return ...;` and TypeScript treats it as defined after that line.
- Give a safe default where one makes sense: `const name = user.name ?? "Guest";`.
- If the value can truly be missing, change the receiving type to accept it (`name?: string` or `string | undefined`).
- Fix the type at the source when it's wrong, for example by regenerating database types.
- Avoid `as any` and avoid the `!` non-null operator unless you're sure; they hide the error and the crash comes back at runtime.
Before
const user = users.find(u => u.id === id);
sendEmail(user.email); // user is possibly undefined
const apiKey: string = process.env.API_KEY;After
const user = users.find(u => u.id === id);
if (!user) throw new Error(`User ${id} not found`);
sendEmail(user.email);
const apiKey = process.env.API_KEY;
if (!apiKey) throw new Error("API_KEY is not set");Tried this and it's still broken? Paste your exact error for a free explanation of your specific case.
Prompt to paste into your AI tool
My build fails with a TypeScript 'Type ... is not assignable to type ...' error (TS2322). Read the exact file and line, explain which value can be undefined or has the wrong type, and fix it with a proper check, a sensible default, or a corrected type. Don't use 'as any' or the non-null '!' operator, and don't change unrelated code.Still stuck?
Paste your exact error and code. Get a plain-English explanation free, or the full fix for $5.
Hitting errors every day? Builder is $15/mo for 100 fixes per month. Compare plans
Related errors
- git push rejected: failed to push some refs
- TypeError: Cannot read properties of undefined
- CORS error: blocked by CORS policy
- Hydration failed: server HTML didn't match the client (Next.js)
Weekly: the errors breaking vibe-coded apps and how to fix them. Free.
No spam. Unsubscribe anytime.