Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript TS2345: Argument is not assignable to parameter

TS2345 marks a call whose argument does not match the parameter type. Compare the call site with the signature, narrow the value, or widen the parameter.

~5 min readTypeScript
#TypeScript#Compiler Errors#Types#Debugging
A TypeScript function crate rejecting an amber argument card at a cyan parameter gate, a widening lever beside it

Introduction & Quick Summary

TS2345 is the compiler refusing a call. The message always has the same shape:

code
error TS2345: Argument of type 'string' is not assignable to parameter of type '"draft" | "published" | "archived"'.

The compiler checked the expression at the call site, compared it with the declared parameter, found no valid assignment, and stopped. The function is fine; the value handed to it does not satisfy the contract in the signature.

Four causes cover most real code:

  • Literal widening. A mutable let or object property widens "draft" to string, which is wider than the union accepted.
  • undefined from lookups. find, Map.get, and JSON.parse results are optional, and the parameter is not.
  • Generic inference. Another argument drove inference to a broader type than the one you passed.
  • Signature variance. A callback with a narrower parameter cannot stand where a wider one is expected under strictFunctionTypes.

Quick summary: read both types in the message, then make the smallest change that makes them agree. Narrow the value at the call site, widen the parameter, or fix the generic. A cast silences the error and moves the failure to runtime, so use it last and document why.

Core Mechanics, Signatures & Reproducible Setup

Assignability is structural. The compiler asks whether every member the parameter requires exists in the argument with a compatible type. For literals the rule is set inclusion: "draft" is assignable to string, but string is not assignable to "draft" | "published", because the compiler cannot prove which member a runtime string holds.

ts
type Status = "draft" | "published" | "archived"; function setStatus(id: string, status: Status): void {} let current = "draft"; // inferred string setStatus("42", current); // TS2345 function findUser(id: string): { name: string } | undefined { return id === "1" ? { name: "Ada" } : undefined; } function greet(name: string): string { return `Hello, ${name}`; } greet(findUser("1")?.name); // TS2345: string | undefined

Reproduce with "strict": true in tsconfig.json and npx tsc --noEmit. The neighbouring diagnostics differ in what they compare, and so does the fix:

DiagnosticWhat it comparesTypical fix
TS2345argument against parameternarrow the value or widen the parameter
TS2322value against variable typefix the annotation or initializer
TS2769call against every overloadmatch one signature or add an overload
TS2739object against a required shapeadd the missing members
TS18048possibly undefined used as a valueguard before use

Key Comparison Table

Each repair has a different blast radius. The table runs from the most local change to the most global.

ApproachChange surfaceCorrect whenRisk
Annotation at declarationone linea literal must stay narrownone, if the annotation is accurate
as const on a literalone expressionfixed tuple or object of literalsvalue becomes readonly
Type guard or early returnone functionthe value is really optionaladds a branch to handle
Widen the parametersignature and callersthe function accepts more than declaredcallers may rely on the narrow type
Generic parameterone signaturethe argument relationship must surviveinference gets harder to read
Explicit type argumentone callinference chose too broad a typehides future inference fixes
Double assertion via unknownone expressionuntyped boundary with validation behind itremoves all checking there

If the value can be undefined at runtime, no type-level trick is honest: handle the branch. If a literal widened, annotation or as const costs nothing.

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Literals widened by let and mutable fields

let widens literals; const keeps them. Mutable object properties widen too.

ts
type Mode = "read" | "write"; declare function open(path: string, mode: Mode): void; let mode = "read"; // string const fixed = "read"; // "read" open("/tmp/a", mode); // TS2345 open("/tmp/a", fixed); // ok const config = { mode: "read" }; // { mode: string } open("/tmp/b", config.mode); // TS2345

Annotate the variable (let mode: Mode = "read") so the check happens where the mistake is introduced, which is the line you want in the error.

2. Optional results from find, get, and index access

find returns T | undefined, and under noUncheckedIndexedAccess a bracket read does too. Passing either into a required parameter is the most common TS2345 in application code.

ts
type User = { id: string; email: string }; declare function sendReceipt(email: string): void; const users: User[] = [{ id: "1", email: "a@example.com" }]; const user = users.find((u) => u.id === "2"); if (!user) throw new Error("user not found"); sendReceipt(user.email); // narrowed to User

user!.email compiles and then throws TypeError: Cannot read properties of undefined for exactly the case the compiler flagged. map.get(key) ?? fallback narrows correctly because the result is no longer optional.

3. Callback variance under strictFunctionTypes

Function type parameters are checked contravariantly, so a handler that requires a narrower event cannot replace one that may receive any event.

ts
type Handler = (event: Event) => void; declare function listen(h: Handler): void; const onClick = (event: MouseEvent): void => console.log(event.clientX); listen(onClick); // TS2345 listen((event) => { // correct: accept, then narrow if (!(event instanceof MouseEvent)) return; console.log(event.clientX); });

Method syntax ({ handle(e: Event): void }) stays bivariant even under strictFunctionTypes, which is why some interfaces accept mismatched callbacks while function type aliases reject them.

4. Generic inference choosing a broader type

When one argument drives inference and another is checked against it, the inferred type can be wider than the value passed.

ts
function first<T>(items: T[], fallback: T): T { return items.length > 0 ? items[0] : fallback; } const n = first([1, 2, 3], "none"); // T = string | number

That compiles, but the return type became a union nobody wanted. Pin it with first<number>([1, 2, 3], 0). When the parameter is what fails, constrain instead of casting: function keys<T extends object>(o: T): Array<keyof T>.

5. Nominal-looking classes and duplicated packages

Classes with identical shapes are structurally compatible unless they carry private or protected members. Those members make the type nominal, and instances from two copies of one package are not assignable to each other.

ts
class Money { private readonly cents: number; constructor(cents: number) { this.cents = cents; } } declare function charge(amount: Money): void; import { Money as OtherMoney } from "some-lib"; charge(new OtherMoney(100)); // TS2345: separate declarations of a private property

The usual cause is two installed versions. npm ls some-lib finds the duplicate; dedupe rather than cast. In monorepos, a relative import that bypasses the package entry point splits the type the same way.

6. Readonly arrays and record types

readonly string[] is not assignable to string[], and a Record<string, string> is not satisfied by values that widened to number.

ts
declare function sortInPlace(values: string[]): void; const names: readonly string[] = ["b", "a"]; sortInPlace(names); // TS2345 declare function toQuery(p: Record<string, string>): string; toQuery({ page: 1 }); // TS2345 toQuery({ page: "1" }); // ok

Accept readonly string[] and copy when mutation is needed. For records, map values explicitly so the conversion is visible and testable.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Casting instead of narrowing. value as Status skips the check that catches a new union member. Prefer a guard that returns, so the compiler keeps proving the type after the branch.
  • @ts-ignore over a real bug. Use @ts-expect-error when a suppression is truly needed; it fails once the error disappears, which keeps it honest across upgrades.
  • Method syntax hides variance. Interfaces with method signatures keep bivariant checks. Switching to property syntax applies the stricter rule and can surface TS2345 in code that compiled before.
  • Minor-version inference drift. TypeScript 5.x changed inference for const type parameters and generic defaults. Pin the compiler and upgrade deliberately.
SymptomActual causeFix
error names a parameter you never wroteoverload resolution failedread the last overload or add one
compiles in one package onlydifferent tsconfig strictnessshare a base config
vanished after as any, returns in testsa null path was hiddenguard at the source
only fails in CIdifferent TypeScript versionpin the compiler

Paste the payload and expected shape into the JSON formatter and validator to confirm what arrives at runtime before choosing which type is honest, and use the text diff tool to compare two versions of a signature or config.

The authoritative references are the TypeScript narrowing handbook for how guards refine types, and the strict family of options for which checks enable together. Read the assignability rules once and most TS2345 messages explain themselves.

Official references

primary documentation

The TypeScript documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.