Sub topic 6
Fixing type mismatches in assignments and calls
This chapter assumes you can run tsc and read a diagnostic's location and code, and that you know basic assignability (a value fits a type if it has everything the type requires). Here you learn to fix the two most common errors, TS2322 and TS2345, by finding where the wrong type came from.
The two error codes
Both errors say that a value's type is not assignable to the type expected at that spot. They differ in where the spot is.
| Code | Where the mismatch happens | Message shape |
|---|---|---|
| TS2322 | Assignment, initializer, property value, or return statement | `Type 'A' is not assignable to type 'B'.` |
| TS2345 | Argument passed to a function call | `Argument of type 'A' is not assignable to parameter of type 'B'.` |
TS2322 covers anything that puts a value into a typed slot. That includes let x: number = "5", returning a string from a function declared to return number, and setting an object property.
let count: number = 0;
count = "five";
function label(n: number): string {
return n;
}The compiler reports TS2322 for count = "five", with the message Type 'string' is not assignable to type 'number'. It reports TS2322 again at return n, with Type 'number' is not assignable to type 'string'. In the second case the declared return type is the contract, and the body breaks it.
TS2345 points at the argument expression, not at the function. The function's parameter type is the requirement, and the argument is what failed to meet it.
Reading the error: expected versus actual
Every mismatch has two types, and your first job is to say which is which.
- The actual type is the type of the value you supplied. It is the first type in the message.
- The expected type is what the slot demands. It is the second type in the message.
Then ask which one is wrong. Sometimes the value is wrong, sometimes the slot's annotation is wrong, and sometimes the value is right but its type was inferred too loosely. The rest of this chapter walks through those three cases.
Case 1: the value is wrong
This is the example that produces a TS2345.
function double(n: number): number {
return n * 2;
}
const input: string = "21";
double(input);Running the compiler in check-only mode prints one line per diagnostic:
$ npx tsc --noEmit --pretty false
src/index.ts(6,8): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.The location (6,8) points at input in the call. The actual type is string and the expected type is number. JavaScript would silently coerce "21" * 2 to 42, but the compiler does not guess. Strings usually reach a number slot from a boundary such as user input, an environment variable, or a parsed file. The correct fix is to convert at that boundary and deal with failure:
function double(n: number): number {
return n * 2;
}
const input: string = "21";
const parsed = Number(input);
if (Number.isNaN(parsed)) {
throw new Error(`Not a number: ${input}`);
}
double(parsed);Note what this does. Number("abc") returns NaN, which is still of type number, so the compiler cannot catch it for you. The isNaN check is what makes the program correct. A shortcut such as double(input as any) would silence the error, but double("abc") would then return NaN at runtime without warning.
Case 2: the value is right but its type was widened
Sometimes you wrote a correct value, and the error still appears. This happens with object literals stored in a const.
type Config = { retries: number; mode: "fast" | "safe" };
function run(config: Config): void {
console.log(config.retries, config.mode);
}
const config = { retries: 3, mode: "fast" };
run(config);This reports TS2345 with a message chain:
Argument of type '{ retries: number; mode: string; }' is not assignable to parameter of type 'Config'.
Types of property 'mode' are incompatible.
Type 'string' is not assignable to type '"fast" | "safe"'.Read the chain from the top. The outer line says the whole object does not fit. The next line narrows it to the property mode. The last line is the root cause: mode has type string, not the union of two literals.
The reason is widening. When TypeScript infers the type of { mode: "fast" }, it assumes the property may be reassigned later, so it gives it the type string. The literal "fast" that you wrote was fine, but the inferred type lost that information.
The fix belongs at the declaration, where the type was lost, not at the call:
type Config = { retries: number; mode: "fast" | "safe" };
function run(config: Config): void {
console.log(config.retries, config.mode);
}
const config: Config = { retries: 3, mode: "fast" };
run(config);With the annotation, the compiler checks the literal against Config directly. The literal "fast" is accepted, and a typo such as "fats" is now reported at the declaration, which is the line where you made the mistake.
Two other fixes work here. as const freezes literals at their narrow types, and satisfies Config checks the object against Config while keeping its inferred type.
type Config = { retries: number; mode: "fast" | "safe" };
const a = { retries: 3, mode: "fast" } as const;
const b = { retries: 3, mode: "fast" } satisfies Config;Use as const when the value should be read-only. It makes every property readonly, which can cause new errors if you pass the object to code that expects mutable properties.
Case 3: the declared type is wrong
The third possibility is that the value is correct and the annotation is too strict. Suppose a function declares id: number but your data source uses string IDs such as "u_42". Every call fails with TS2345. Changing each caller would be the wrong move. The signature does not describe your data, so change the signature:
function findUser(id: string): string {
return `user:${id}`;
}
findUser("u_42");If both forms are valid, widen deliberately with a union (id: string | number). Then handle both inside the function with typeof narrowing. Widen a parameter only when the function can actually handle every member of the union. Otherwise you move the error inside the function body.
Choosing where to fix
A mismatch can be fixed at several places, and the best place is usually the one closest to where the wrong information entered.
- If data came from outside the program (input, JSON, environment), validate and convert it there.
- If an inferred type is too wide, annotate the variable or use
as constorsatisfies. - If the function's contract is wrong for all callers, change the signature.
- If you know something the compiler cannot prove, use an assertion, and only after checking the first three options. Assertions are covered in a later chapter.
Common mistakes
- Fixing the call when the declaration is the problem. If the same variable fails at three call sites, the fix is almost always at the one declaration.
- Reading only the first line of a chain. For nested messages, the last indented line names the real cause.
- Adding
anyto make the error disappear. It removes checking for that value and for everything derived from it. - Treating
NaNas a type error.NaNhas typenumber, so only a runtime check catches it.
Exercise
The compiler reports TS2345 on the call run(settings), with the final chain line "Type 'string' is not assignable to type '"on" | "off"'." The declaration is const settings = { power: "on" };. Where should you fix it, and how?
Show answer
Fix it at the declaration, not at the call. The property power was widened from the literal "on" to string. Annotate the variable with the intended type (for example const settings: Settings = { power: "on" };) or use as const or satisfies. The literal itself was correct.
Exercise
A function declared function total(items: number[]): number returns items.join(","). Which error code do you get, and what are the actual and expected types?
Show answer
TS2322, because the mismatch is in a return statement, not a call argument. The actual type is string (the result of join), and the expected type is number (the declared return type). Fix the body to compute a sum, or change the return type if a string is what you really want.