Why even in strict mode TypeScript is not complaining about this
Create a type-safe variadic function to do concatenation for you.
concat(...strings: string[]): string {
var concatenated = "";
for (var i = 0; i < strings.length; i++) {
concatenated += strings[i];
}
return concatenated;
};
Now when you concatenate, use your function:
const str: string = '';
const num: object = {};
const result: string = concat(str, num); // throws error
Example here
In the context of the + operator, you can't, because it's designed to be able to support mixed types, for example in the expression "Count: " + a.length()
.
The conversion of objects to strings can be implied (in + concatenation) and controlled. In modern JavaScript this might be demonstrated as follows:
let o = {};
o.toString = ()=> "two"
alert("one" + " " + o); // Displays "one two"
So there isn't really a reason to reject the second example just based on types.
As to the first example, conversion from unknown
and null
to string are implied and defined in abstract ToString() operation, though I'm not sure it's changeable, it seems well defined. Now, it certainly might be reason to flag with a tool like tslint, but it remains a valid operation in ECMAScript.
Because it is valid to concatenate strings and undefined values. Same issue for your second example. In JavaScript, your can '' + {}
(would not be of much use though, typically).
Strict typing prevents unsafe access like lastName.length
in your example.