- Error
- Reported by the type checker
TS2322
Type '{0}' is not assignable to type '{1}'.
A value is assigned to a variable, property or return type it doesn't fit. Change the value, or widen the declared type if the value is legitimate.
What it means
A value of one type is used where another type is required, and the first isn't assignable to the second. It's reported on assignments, variable initialisers, property values in object literals, return statements and default values. When the mismatch is deep inside an object type, the message has extra indented lines that walk down to the property that doesn't fit.
Example
let count: number = 0;
count = "1";
ts-r-check -p tsconfig.json --pretty false ts-r outputindex.ts(2,1): error TS2322: Type 'string' is not assignable to type 'number'.
Recorded by node scripts/verify-examples.mjs with ts-r built from commit 6deaf01. The example uses the default tsconfig: strict, target: es2022, module: esnext, moduleResolution: bundler.
How to fix
- Convert the value:
count = Number("1"), or parse it if it comes from outside the program. - If the value is legitimately of both kinds, widen the declared type:
let count: number | string. - For object literals, read the indented lines of the message: the last one names the property that doesn't match.
- Avoid silencing it with
as: an assertion tells the checker to trust you, and the runtime value is still wrong.