I've tried to find an explanation in the TypeScript docs of why my transpiled JavaScript is now using String.concat() when it used to use the addition operator. I can't determine what in my project or tool chain changed to cause the difference in the transpiled files. Let me provide an example of what I'm trying to describe.
Transpiled TypeScript files from a few months ago would transpile this TypeScript:
`Order #${order.tranid} (IID ${order.id}) is ineligible for processing - exiting`
into this JavaScript:
"Order #" order.tranid " (IID " order.id ") is ineligible for processing - exiting"
Now when I work with this project, the same TypeScript will generate:
"Order #".concat(order.tranid, " (IID ").concat(order.id, ") is ineligible for processing - exiting"
My question is: Does anyone here know what could be responsible for the different output? Was this a change to the compiler recently? As I mentioned at the beginning, I can't find anything in my searches that explains it.
CodePudding user response:
The change was implemented to make transpiled TypeScript template strings more spec compliant with native template literals.
This was tracked in TypeScript issues #39744 and #43686.
The change was publicly released in TypeScript 4.4.2 (4.4.0 and 4.4.1 were beta and RC versions, respectively).
There is a related comment in that thread that indicated that the previous
string concatenation would throw errors with the upcoming Temporal proposal as well.
Using the example from the Github issue:
class C {
toString() {
return "toString()";
}
valueOf() {
return "valueOf()";
}
}
const c = new C;
const s = `${c}`;
console.log(s);
The expected result, as defined by the JavaScript spec for template literals, should be toString()
.
However, because TypeScript was transpiling down to use the string concatenation operator
it would return the incorrect toValue()
.
By changing to string.concat()
transpiled TypeScript code now returns the correct toString()
result.
Note, this was only an issue if TypeScript was transpiling down to ES3 or ES5.