0

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?

5
  • 1
    Basically, although the + will definitely work in Javascript, its behaviour when arg1 is a number depends on whether arg2 is 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. The add2 function has no error because the behaviour is definitely string concatenation, not ambiguous. Commented Dec 12, 2019 at 14:20
  • ok @kaya3 so why in the first if it's work even without the condition in and? Commented Dec 12, 2019 at 14:25
  • 1
    Does this answer help? Basically it is treated as safe to apply the + operator to string|number and string, but not when the operands are string | number and number. At least one has to be string (see the quotings from the specs in the answer). Commented Dec 12, 2019 at 14:41
  • 1
    In the first if statement, where arg1 is definitely a string, then + is definitely string concatenation regardless of the type of arg2, so it's not ambiguous. Commented Dec 12, 2019 at 14:48
  • @ford04 not I don't understand even in your exaple in the tabelle there is that number+string is allowed ad return a string exactly as in my add2 function. so why I need the condition in and in the second if? Commented Dec 12, 2019 at 14:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.