When comparing TypeScript to Java/C#, it is important to note that in JavaScript, type is not enforced at runtime. This means there are no casting errors or type conversion errors to worry about, as all type restrictions in TypeScript are only present in the Editor and Compiler. Once compiled, these types are no longer relevant. Additionally, JavaScript does not support function overloading due to its lack of type restrictions, allowing any type of object to be passed as an argument.
In the case of Function overloads, they are simply declarations and do not automatically detect errors based on implementation. Errors are only detected based on the specified types.
The function
concat5<T>(strs: T, strs2: T): T;
indicates that both
strs
and
strs2
should be of the same type, without restricting the possible type of
T
.
An error is encountered when the implementation does not match the declaration, as seen in the following example:
function concat5<T>(strs: T, strs2: number): T;
function concat5(strs: string, strs2: string) {
return strs + strs2;
}
However, in cases like the following examples, where JavaScript can accept any object as a string input and convert it eventually, no error is thrown even if the parameters are not explicitly specified:
function concat5<T extends number>(strs: T, strs2: T): T;
function concat5(strs: string, strs2: string) {
return strs + strs2;
}
function concat5<T1 extends number, T2>(strs: T1, strs2: T2): T1;
function concat5(strs: string, strs2: string) {
return strs + strs2;
}
This lack of error occurs because JavaScript can handle any object for string input by converting them to strings. As long as the parameters are not explicitly specified, the implementation is considered correct.
For some fun: Try typing {} + {}
in Chrome's console for a surprising result of [object Object][object Object]
. This showcases JavaScript's ability to concatenate any two types, converting them to strings.
>{} + 2
< 2
>2 + {}
<"2[object Object]"
>null + 2
<2
>2 + undefined
<NaN
>2 + (function(){ return 3; })
<"2function(){ return 3; }"