Skip to content

/errors/typescript/ts2322-type-is-not-assignable-to-type

error TS2322: Type 'string' is not assignable to type 'number'

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · v24.20.0updated
tool
TypeScript
exit code
2
versions
TypeScript 5.x
os
any

error TS2322: Type 'A' is not assignable to type 'B' means TypeScript found a value of type A where the declared type is B, and A is not compatible with B. TypeScript never converts values for you: convert the value (Number(input)), narrow it with a check, or correct the type annotation if it is the annotation that is wrong.

Reproduce it

bash
npm init -y >/dev/null
npm install --silent --no-audit --no-fund typescript@5 >/dev/null 2>&1
cat > app.ts <<'EOF'
const input: string = "8080";
let port: number = input;

interface User { id: number; name: string }
const user: User = { id: "1", name: "Ada" };

function parsePort(value: string | undefined): number {
  return value;
}
EOF
npx tsc --noEmit --strict --pretty false app.ts

Output · exit 2

app.ts(2,5): error TS2322: Type 'string' is not assignable to type 'number'.
app.ts(5,22): error TS2322: Type 'string' is not assignable to type 'number'.
app.ts(8,3): error TS2322: Type 'string | undefined' is not assignable to type 'number'.
  Type 'undefined' is not assignable to type 'number'.

The location app.ts(2,5) is line and column. For object literals the error points at the property and names the expected type from the interface; for return values it names the declared return type.

Fixes

bash
npm init -y >/dev/null
npm install --silent --no-audit --no-fund typescript@5 >/dev/null 2>&1
cat > app.ts <<'EOF'
const input: string = "8080";
let port: number = Number(input);

interface User { id: number; name: string }
const user: User = { id: Number("1"), name: "Ada" };

function parsePort(value: string | undefined): number {
  if (value === undefined) return 3000;   // narrowing removes undefined
  return parseInt(value, 10);
}
console.log(port, user.id, parsePort(undefined), parsePort("8443"));
EOF
npx tsc --strict --pretty false app.ts && node app.js

Output

8080 1 3000 8443

Sources