Why TypeScript lets me add a string and a number? Can I prevent it?

“It’s valid because it’s valid in JS” is a non-answer in the context of why a certain operation isn’t a type error; see What does “all legal JavaScript is legal TypeScript” mean?

In JavaScript, code like alert("Your position in the queue is " + queuePos) is idiomatic and common — it is not commonly written as "str" + num.toString().

TypeScript’s position is that idiomatic JS should not cause type errors (when practical). This means that string + number is an allowed coercion.

The question of what += should do is then a matter of choosing between two options:

  • consistency: x = x + y should be identical to x += y
  • safety: x += y is not commonly done between string and number operands, so should be an illegal coercion

Both choices are sensible and defensible; TypeScript happened to choose the first.

Leave a Comment