Skip to content

TS2322: Type Is Not Assignable to Type — Causes and Fixes

TS2322: Type 'X' is not assignable to type 'Y' means a value doesn't fit the slot you put it in. How to read the indented lines under it, the four causes behind most of them, and fixes that don't involve as any.

ts2322 assignability literal-types strict-mode type-errors typescript js-ts-errors
BKG
Reading Progress

On This Page

const seats: number = form.seats;

That line, in a booking-calendar form handler, is the whole bug. The seat count came out of an HTML input, so it's a string, and the variable says number. TypeScript refuses with TS2322, "type is not assignable to type", and most of the top search results tell you to cast it away.

Don't. Every TS2322 is TypeScript pointing at a line where your code and your types disagree about what a value is. Sometimes the types are wrong. More often the code is.

The error, four times over

Here's what TypeScript 6.0.3 printed for a small booking module, on Node 22.23.5 in a Linux container, with tsc -p .:

src/booking.ts(19,7): error TS2322: Type 'string' is not assignable to type 'number'.
src/booking.ts(23,7): error TS2322: Type '{ room: string; size: string; seats: number; guestEmail: string; }' is not assignable to type 'Booking'.
  Types of property 'size' are incompatible.
    Type 'string' is not assignable to type 'RoomSize'.
src/booking.ts(26,7): error TS2322: Type 'Guest | null' is not assignable to type 'Guest'.
  Type 'null' is not assignable to type 'Guest'.
src/booking.ts(30,9): error TS2741: Property 'email' is missing in type 'Promise<Guest>' but required in type 'Guest'.
src/extra.ts(3,9): error TS2322: Type 'Promise<string>' is not assignable to type 'string'.
src/extra.ts(8,5): error TS2322: Type 'string' is not assignable to type 'RoomSize'.

Same code, four different stories. A string where a number belongs. A literal that widened to string. A null that the type doesn't allow. A missing await. And notice line 30: the missing await on an object-returning call didn't come out as TS2322 at all. It came out as TS2741, because when the target is an object type TypeScript prefers to tell you which property is missing. That one caught me out, and I'll come back to it.

TypeScript 5.9.3, 6.0.3 and 7.0.2 (the native Go compiler) printed the same text for every one of these in my lab. With --pretty you also get a code frame, and 7.0 puts the "declared here" pointer on one line instead of two.

Editor, compiler, or runtime?

TS2322 is raised by the TypeScript type checker. The same checker runs in two places: the language service behind your editor's red squiggles, and tsc on the command line or in CI. It never comes from Node, the browser or a bundler. Vite, esbuild, tsx and Node's type stripping remove types without checking them, so a project can run fine with a dozen TS2322s in it. That's not a sign the errors are harmless. It's a sign nothing is checking.

The two-minute triage:

npx tsc --version                 # the compiler your project actually installed
npx tsc --noEmit --pretty false   # every error, one per line, no editor in the way
npx tsc --showConfig              # the options you set, after extends

If the editor shows TS2322 and tsc doesn't, or the reverse, the editor is almost always using a different TypeScript version or a different tsconfig.json than the command line. That's its own article: TypeScript errors in CI but not in VS Code.

My first wrong turn is worth sharing here. The null error on line 26 only appeared after bumping the project from TypeScript 5.9.3 to 6.0.3, with no code change. I assumed a regression in how findGuest() was typed and went looking through the declaration. It was fine. Then I ran --showConfig, which printed target, module, noEmit, moduleResolution and moduleDetection, and no strict at all. So strict was off, right? Wrong. --showConfig prints what you set plus a few implied options; it doesn't print defaults, and TypeScript 6.0 made strict: true the default. The tsconfig hadn't changed. What the missing line meant had.

Break it on purpose, with three compilers

Do this in a throwaway folder, not your real repo.

What you need: Node 20.19 or newer (I used 22.23.5), npm, and three pinned TypeScript versions from the npm registry: typescript@5.9.3, typescript@6.0.3 and typescript@7.0.2.

  1. Create the project and install 6.0.3 as the main compiler:
mkdir ts2322-lab && cd ts2322-lab
npm init -y
npm install -D typescript@6.0.3
mkdir src
  1. Add a tsconfig.json that deliberately says nothing about strictness:
{
  "compilerOptions": {
    "target": "es2022",
    "module": "nodenext",
    "noEmit": true
  },
  "include": ["src"]
}
  1. Add src/booking.ts:
type RoomSize = "small" | "large";

interface Booking {
  room: string;
  size: RoomSize;
  seats: number;
  guestEmail: string;
}

interface Guest {
  email: string;
}

declare function findGuest(id: string): Guest | null;
declare function loadGuest(id: string): Promise<Guest>;

const form = { room: "B-12", seats: "6" };
const seats: number = form.seats; // input values are strings: TS2322

const draft = { room: "B-12", size: "small", seats: 6, guestEmail: "a@example.com" };
const booking: Booking = draft; // "small" widened to string: TS2322

const guest: Guest = findGuest("g-41"); // can be null: TS2322 under strict

async function confirm(id: string) {
  const g: Guest = loadGuest(id); // forgot await: TS2741, not TS2322
  return g.email;
}

export { seats, booking, guest, confirm };
  1. Type-check with each compiler:
npx tsc -p .                          # 6.0.3, four errors, exit code 2
npx -p typescript@5.9.3 tsc -p .      # three errors, no null error, exit code 2
npx -p typescript@7.0.2 tsc -p .      # four errors, exit code 1

You've reproduced it when 6.0.3 prints error TS2322: Type 'Guest | null' is not assignable to type 'Guest'. and 5.9.3 doesn't. That gap is the strict default, nothing else. If you see TS2345 instead of TS2322, you passed the value as a function argument rather than assigning it; same mechanism, different code, covered in TS2345: Argument of type is not assignable to parameter.

One oddity: with noEmit: true, 7.0.2 exited with 1 where the others exited with 2 (with emit on, all three returned 2). A script that tests for exactly 2 will notice.

Teardown: delete the ts2322-lab folder. The npx -p runs leave copies in npm's cache, which is harmless.

The short answer

TS2322 means: you wrote a type on the left (a variable annotation, a return type, a property type) and the value on the right has a type that doesn't fit inside it. TypeScript compares the two by shape, member by member, and reports the first place they disagree. The fix is to change whichever side is lying.

Why the compiler compares shapes, and where it gave up

TypeScript uses structural typing: a type is compatible with another if it has the right members with the right types, regardless of what either is called. So { room: string; size: string; seats: number; guestEmail: string } is checked against Booking property by property. Three properties pass. size doesn't, because string is wider than "small" | "large".

That's what the indented lines are. They're the elaboration chain: each line goes one level deeper into the comparison until TypeScript hits the leaf that failed. Read them bottom-up. The last line, Type 'string' is not assignable to type 'RoomSize', is the real problem. The top line only tells you which statement it happened in. On big types the chain can run 20 lines; the bottom-up rule still holds, and there's a whole piece on it: how to read a long TypeScript error.

Now, why did "small" become string? Widening. When you write const draft = { size: "small" }, TypeScript infers the property as string, because object properties are mutable and you might assign "huge" to it later. A plain const x = "small" keeps the literal type "small", because a const variable can't change. The literal survives on bare constants and dies inside objects and arrays (["small", "large"] is string[]). That's the whole reason sizes[0] failed in extra.ts.

The null case is the strictness flag strictNullChecks, which strict turns on. Without it, null and undefined are quietly members of every type, so Guest | null collapses to Guest and the check passes. With it, null is its own type and has to be dealt with. Five of the six errors survived when I set "strict": false under 6.0.3 and 7.0.2. The one that vanished was the one most likely to crash in production. The flags strict enables are listed in the strict reference and covered in TypeScript strict mode explained.

And the missing await. A Promise<Guest> is an object with then, catch and finally, not an object with email. When the target is an object type, the checker goes looking for which required properties are missing and reports TS2741 with "Property 'email' is missing". When the target is a primitive like string, there are no properties to list, so you get TS2322 with Type 'Promise<string>' is not assignable to type 'string'. Same bug, two codes. I'd half-expected a "Did you forget to use 'await'?" hint here; none of the three compilers printed one for a plain assignment.

Fixing each one without lying to the compiler

Before the fixes, the non-fixes. as any makes the error disappear by telling the checker to stop checking that value, everywhere it flows. // @ts-ignore does the same for one line and keeps doing it after the line changes. as unknown as Booking is a double cast that compiles anything into anything. And "strict": false in TypeScript 6 brings back the 5.x behaviour where null fits everywhere. All four move the crash to runtime. None of them is a fix.

Here's the fixed module. It passes on 5.9.3, 6.0.3 and 7.0.2 with exit code 0:

// 1. Convert at the boundary, and decide what a bad value means
const form = { room: "B-12", seats: "6" };
const parsed = Number.parseInt(form.seats, 10);
if (Number.isNaN(parsed)) throw new Error(`seats is not a number: ${form.seats}`);
const seats: number = parsed;

// 2. Check the literal against the type where you write it
const draft = {
  room: "B-12",
  size: "small",
  seats: 6,
  guestEmail: "a@example.com",
} satisfies Booking;
const booking: Booking = draft;

// 3. Decide what null means
const found = findGuest("g-41");
if (!found) throw new Error("guest g-41 not found");
const guest: Guest = found;

// 4. Await it
async function confirm(id: string) {
  const g: Guest = await loadGuest(id);
  return g.email;
}

// Arrays of literals: freeze them
const sizes = ["small", "large"] as const;
let pick: RoomSize = sizes[0];

When there's more than one valid fix, pick by what the value really is:

Cause Fix Use it when Cost
Wrong primitive (string into number) Convert with Number() or parseInt, then validate The data really arrives as a string (forms, query strings, process.env) One check per boundary, which you needed anyway
Literal widened to string satisfies Booking on the literal, or annotate it const draft: Booking = … You build an object that's meant to be a specific type None at runtime
Literal array widened to string[] as const Fixed lists of allowed values The array becomes readonly
T \| null into T Narrow with an if, a default with ??, or widen the target type to allow null null is a real outcome (not found, not loaded yet) You have to decide what happens in that case. That's the point
Promise<T> into T await it, or type the variable as Promise<T> You need the value now The function becomes async

satisfies (TypeScript 4.9 and later) is the one people underuse. It checks the object against Booking at the spot you wrote it, which gives the error on the actual typo, and it keeps the narrow inferred type, so draft.size stays "small". A plain annotation also works and is fine when you don't need the narrow type. Prefer satisfies over as Booking: an as assertion only complains when the types barely overlap at all (TS2352 covers that), so it happily accepts "smal".

In a real codebase, run npx tsc --noEmit --pretty false, take the last indented line of each error, and ask where the right-hand type came from. Usually it's a helper three files away: a function with no return type that inferred string, or a fetch wrapper typed Promise<any>.

Getting the types right up front

Most TS2322s I see trace back to untyped boundaries. Data enters as string or any (a form, a URL, an API, an env var) and the types downstream assume it's already clean. So type the boundary once:

interface BookingInput {
  room: string;
  size: string;
  seats: string;
}

function toBooking(input: BookingInput, guestEmail: string): Booking {
  const seats = Number.parseInt(input.seats, 10);
  if (Number.isNaN(seats) || seats < 1) throw new Error(`bad seat count: ${input.seats}`);
  if (input.size !== "small" && input.size !== "large") throw new Error(`bad size: ${input.size}`);
  return { room: input.room, size: input.size, seats, guestEmail };
}

After the if on input.size, TypeScript has narrowed string down to "small" | "large", so the return statement passes with no cast. Everything past toBooking gets a real Booking. For bigger payloads a schema validator does the same job with less typing, but the shape of the idea doesn't change: unknown or string at the edge, a real type inside.

Write "strict": true into tsconfig.json even on TypeScript 6, so humans and --showConfig both see it, and put return types on exported functions so a wrong inference fails at the function, not three call sites away.

What to check in CI

  • Run tsc --noEmit as its own required step. Your bundler won't do it for you.
  • Pin TypeScript to an exact version in package.json ("typescript": "6.0.3", no caret), so a minor release can't add errors on a random Tuesday.
  • Write "strict": true in tsconfig.json explicitly.
  • Turn on typescript-eslint's no-explicit-any, and ban @ts-ignore in favour of @ts-expect-error with a reason. @ts-expect-error fails the build once the error underneath is fixed, so it can't rot.

Version notes. The TS2322 wording is the same on 5.9, 6.0 and 7.0. What changed is how many you get: moving from 5.x to 6.0 with no strict setting turns on strictNullChecks, and every T | null into T assignment becomes a new TS2322. That's usually the biggest batch after the bump (TypeScript 6 upgrade errors has the rest).

Scope, for the record: every variant above, on three pinned compilers, with strict implied and switched off, plus the fixed code, checked against the 6.0 release announcement. I didn't test VS Code itself for this one.

If you remember nothing else

  • Read the indented lines bottom-up. The last one is the real mismatch.
  • "small" inside an object or array becomes string. satisfies or as const keeps it.
  • A new pile of null TS2322s after a TypeScript 6 upgrade means strict turned on by default. Those lines were already able to crash.
  • A missing await shows up as TS2322 for primitives and as TS2741 for objects.
  • If the fix involves as any, @ts-ignore or a double cast, you haven't found the cause yet.

Questions people search for

How do I fix "Type 'string' is not assignable to type 'number'" in TypeScript?

Convert the value where it enters your code, usually with Number() or Number.parseInt(value, 10), then check for NaN before using it. Values from forms, query strings and process.env are always strings at runtime, so the type is telling the truth. Don't annotate the input as number to make the error go away; that only hides the conversion you still need.

Why does TypeScript say my string literal isn't assignable to a union type?

Because the literal widened. Inside an object or array, "small" is inferred as string, which is wider than "small" | "large". Use satisfies YourType on the object, annotate the variable with the type, or add as const to the array (TypeScript 4.9+ for satisfies).

What's the difference between TS2322 and TS2345?

TS2322 fires on assignments, return statements and property values. TS2345 is the same check when the value is a function argument: "Argument of type X is not assignable to parameter of type Y". The causes and fixes are the same, and TS2345 has the narrowing patterns for string | undefined arguments.

ts2322assignabilityliteral-typesstrict-modetype-errorstypescriptjs-ts-errors

BKG

Engineer and writer behind CODELZ. I read the stack trace, reproduce the bug, and explain why it happens, not just how to silence it. Plus honest reviews of the books and tools worth your time.

Comments