“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 tox += y
- safety:
x += y
is not commonly done betweenstring
andnumber
operands, so should be an illegal coercion
Both choices are sensible and defensible; TypeScript happened to choose the first.