Home·Error messages

tsc · Build and types

The message

error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

What it means

The type the function accepts and the type you passed are different, and the message states them in order — the first is what you gave, the second is what it wanted. The most common case by far is a value from a form field, a URL query string or JSON arriving as a string where a number is expected. Converting once at the boundary is the answer, but Number(value) returns NaN rather than throwing when it fails, so you have to stop that NaN from travelling — Number.isFinite(n) is the check that belongs there.

The fix

There is no one-line command for this. The explanation says what to look at instead.

Printed by
tsc
Build and types
10

Build errors are a tool refusing before anything runs, so they break nothing at the moment they appear — but they do ask two questions: will you fix the type or the path to match the real shape, or will you push that one line through with an as any or a suppression comment — and it is here that the things which are only true on your own machine, letter case, extensions and environment variables, show themselves for the first time.

Reading an error message

  • Read from the first line down. The lower you go the more it is about the tool’s internals; the cause is usually at the top.
  • If there is a file and a line number, start there — not the top stack frame, but the topmost line that names a file you wrote.
  • Search the message verbatim, but strip your own paths and variable names first; those are what stop the search from matching.
  • The same condition is worded differently across tool versions. If results look wrong, add the version number to the query.
  • Before pasting a fix, check what it throws away. Some of these cannot be undone.

Common questions

Q. What does “error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.” mean?

The type the function accepts and the type you passed are different, and the message states them in order — the first is what you gave, the second is what it wanted. The most common case by far is a value from a form field, a URL query string or JSON arriving as a string where a number is expected. Converting once at the boundary is the answer, but Number(value) returns NaN rather than throwing when it fails, so you have to stop that NaN from travelling — Number.isFinite(n) is the check that belongs there.

Q. How do I fix it?

There is no one-line command. The explanation above says what to look at instead.

Q. Which tool prints this?

tsc. It sits under Build and types, and the message runs to 14 words.

Errors nearby