I'm afraid that there is currently no way of preventing such a conversion, aside from building an abstraction of your own. Something like this (admittedly, not very elegant):
function safe_add(x: string, y: string): string { return x + y; }
let x = "1";
x = safe_add(z, 1); // Argument of type '1' is not assignable to parameter of type 'string'.
The usual policy of TypeScript's type checking, according to "All legal JavaScript is legal TypeScript", is to prevent situations which are clearly wrong and never actually useful. For example, passing a string to Math.max
is prevented. Unlike this example however, the +
operator between a string and a number, despite not always desirable, is indeed a valid operation, and is employed too often in practice to be barred by the compiler. As x += y
is equivalent to x = x + y
, and always resulting in a string when x
is a string, the assignment itself is also valid. This is one of those cases that are most likely going to remain as OK by the compiler. Issue #20131 aims to make a few more operations throw a warning, but this one in particular is not included.
As you might already understand, the opposite is successfully prevented, since a variable is not expected to change its type with the add-assignment operator.
let y = 1;
y += "1"; // Type 'string' is not assignable to type 'number'
See also: