Why ‘X’ + Y = ‘XY’ in TypeScript ? Expect an error

In TypeScript, when a string is concatenated with a non-string value using the “+” operator, the non-string value is implicitly converted to a string before concatenation. This is known as type coercion. This is why the expression ‘X’ + Y results in ‘XY’ instead of an error.

For example, in the following code snippet, the variable Y is of type number, but it gets implicitly converted to a string before getting concatenated with ‘X’:

let Y = 10;
let result = 'X' + Y;
console.log(result); // Output: 'X10

This behavior is not specific to TypeScript, but it’s common in many programming languages. This is because the + operator is overloaded in many languages, it can be used for both mathematical addition and string concatenation. If one operand is a string, the other is converted to a string, then concatenation is applied.

However, if you want to avoid this behavior, you can use a more explicit way of converting a non-string value to a string, such as using the String() function or the template literals \ `.

let Y = 10;
let result = 'X' + String(Y);
console.log(result); // Output: 'X10'

let result2 = `X${Y}`;
console.log(result2); // Output: 'X10'

In this way, you can avoid unexpected behavior, and also make your code more readable.

Leave a Reply