Why even in strict mode TypeScript is not complaining about this
function test(firstName: string, lastName?: string): string {
return firstName + " " + lastName;
}
test('John');
Nor about this
const str: string = '';
const num: object = {};
const result: string = str + num;
I don't remember cases when I would want to get and print on the screen 'John undefined' or '[object Object]'. Is the whole point of type checking is supposed to be catching such errors? (Flow does it)
Create a type-safe variadic function to do concatenation for you.
Now when you concatenate, use your function:
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:
So there isn't really a reason to reject the second example just based on types.
As to the first example, conversion from
unknown
andnull
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.