I find an example to explain Type guards in Typescript but I don't understand, why this code work:
function add(
arg1:string|number,
arg2:string|number
):any{
if (typeof arg1==="string"){
console.log("string")
return arg1+arg2;
}
if (typeof arg1==="number" && typeof arg2==="number"){
console.log("number")
return arg1+arg2;
}
return arg1.toString()+arg2.toString()
}
console.log (add(1,2));
and why doesn't work, if you change the second if like this:
if (typeof arg1==="number" ){...
without the condition in and doesn't work even if this function work:
function add2():any{
return (2+"3")
}
console.log(add2())
So why I have to put the condition in and ? otherwise give an error?
+will definitely work in Javascript, its behaviour whenarg1is a number depends on whetherarg2is a string or a number; normally, when you write+you should know whether you want string concatenation or numeric addition, so Typescript reports an error when the+operator is ambiguous. Theadd2function has no error because the behaviour is definitely string concatenation, not ambiguous.+operator tostring|numberandstring, but not when the operands arestring | numberandnumber. At least one has to bestring(see the quotings from the specs in the answer).ifstatement, wherearg1is definitely a string, then+is definitely string concatenation regardless of the type ofarg2, so it's not ambiguous.