Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Next.js and React

TypeScript still says string | undefined although I checked the value

Your error

Type 'string | undefined' is not assignable to type 'string'. ts(2322)2 more lines it can show

Fix it fast

Most common cause, 1 of 3

The value is read in a callback while it can still change

Copy the checked value into a const once, test the const, and use only the const inside callbacks.

Fix
function Profile({ user }: { user?: { email?: string } }) {
  const [to, setTo] = useState('');
  const email = user?.email;      // one const, checked once
  if (!email) return null;

  const onInvite = () => setTo(email); // email is string here
  return <button onClick={onInvite}>Invite</button>;
}
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

Type 'string | undefined' is not assignable to type 'string' after an if check means the narrowing never reached the failing line. A later callback, a helper typed as boolean or a computed obj[key] lookup drops it. Copy the value into a const, give the helper a type predicate, or test the exact expression. Applies to TypeScript 5.5 to 7.0.

  • Applies to TypeScript 5.5, 6.0 and 7.0, React 19.3, @types/react 19
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

List every assignability error with its line, then look at where each one sits compared with the check. Inside an arrow function or effect points to cause 1, an if around a helper call such as isValid(x) to cause 2, and a lookup in square brackets to cause 3.

Run this first
npx tsc --noEmit --pretty false | grep -E "TS2322|TS2345"

Then find the line you see in this list and open its fix:

  1. 1The value is read in a callback while it can still changeThe error is inside an arrow function passed to map, useEffect, setTimeout or an event handler, while the same expression type-checks on the line right after the if
  2. 2The check lives in a helper typed as booleanThe guard is a call such as isFilled(value), and hovering value inside the if still shows string | undefined
  3. 3A computed lookup is checked and then read againThe code tests errors[field] or values[key] and then passes the same bracket lookup on, while field or key is a let variable or changes in between

What does the error look like?

  • Type 'string | undefined' is not assignable to type 'string'. ts(2322)
  • Argument of type 'string | undefined' is not assignable to parameter of type 'string'. ts(2345)
  • Type 'undefined' is not assignable to type 'string'.

Cause 1 of 3

The value is read in a callback while it can still change

You seeThe error is inside an arrow function passed to map, useEffect, setTimeout or an event handler, while the same expression type-checks on the line right after the if

Check

When 'string | undefined' is not assignable to 'string' inside a callback, the narrowing from the outer if did not carry into that function. Since TypeScript 5.4, a parameter or let variable keeps its narrowed type in a non-hoisted function created after its last assignment. It still loses it when the variable is assigned again later, when any nested function assigns it, and inside hoisted function declarations. Older versions dropped it in closures far more often.

Check
grep -n -E "^\s*(let |[a-zA-Z_]+ = )" src/components/Profile.tsx

Fix

Copy the checked value into a const once, test the const, and use only the const inside callbacks. A const can never be reassigned, so its narrowed type holds in every function below the check. Move any later reassignment of the original variable above the callback, or drop it.

Fix
function Profile({ user }: { user?: { email?: string } }) {
  const [to, setTo] = useState('');
  const email = user?.email;      // one const, checked once
  if (!email) return null;

  const onInvite = () => setTo(email); // email is string here
  return <button onClick={onInvite}>Invite</button>;
}

Verify

The type check passes and hovering the const inside the callback shows string.

Verify
npx tsc --noEmit

Confirmed by typescriptlang.org

Did this fix it?

Cause 2 of 3

The check lives in a helper typed as boolean

You seeThe guard is a call such as isFilled(value), and hovering value inside the if still shows string | undefined

Check

TypeScript narrows through a function call only when the function returns a type predicate, written as parameterName is Type. A helper annotated : boolean gives it no link between the result and the argument, so the value stays string | undefined after the call. TypeScript 5.5 infers a predicate on its own only for a helper with no return type annotation, a single return statement and an unchanged parameter.

Check
grep -rn -E "function is[A-Z][a-zA-Z]*\(.*\): boolean" src/

Fix

Declare the predicate on the helper. Keep the body exactly as strict as the predicate claims, because in the else branch TypeScript assumes the opposite type.

Fix
function isDefined<T>(value: T | undefined): value is T {
  return value !== undefined;
}

if (isDefined(form.email)) {
  sendInvite(form.email); // string
}

Verify

The call site compiles without a cast or a non-null assertion.

Verify
npx tsc --noEmit

Confirmed by typescriptlang.org

Did this fix it?

Cause 3 of 3

A computed lookup is checked and then read again

You seeThe code tests errors[field] or values[key] and then passes the same bracket lookup on, while field or key is a let variable or changes in between

Check

TypeScript narrows an expression of the form obj[key] only when both obj and key are effectively constant, and only from version 5.5. If the key is reassigned, or the project still compiles with an older TypeScript, each lookup is typed from scratch as string | undefined, so the earlier check counts for nothing.

Check
npx tsc --version

Fix

Read the entry once into a const, test the const and pass the const on.

Fix
const message = errors[field];
if (message) {
  setFieldError(message); // string
}

Verify

tsc reports no TS2322 or TS2345 on that line.

Verify
npx tsc --noEmit --pretty false | grep -c -E "TS2322|TS2345"

Confirmed by typescriptlang.org

Did this fix it?

How do I stop it coming back?

  • Keep typescript at 5.5 or newer in package.json, so the closure rules from 5.4 and the indexed-access narrowing from 5.5 apply.
  • Type every guard helper with a predicate such as value is T, never a plain boolean, and keep the helpers in one shared module.
  • Store a value you check and then use in handlers or effects in a const near the top of the component.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: TaxiDex, QistLock, Taskvare.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.