Problems caused by union types in typescript in operators

the following is the code I wrote while debugging, but I reported an error

function fn (x: number | string,y: number | string){
    return x+y 
}

but it"s okay to write like this

function fn (x: number,y: string){
    return x+y 
}

the following way of writing will also report an error

function fn (x: number | string,y: number){
    return x+y 
}

in my understanding, the + operation is the common operation symbol of number and string. Why does it report an error?

Feb.28,2022

bug.. Bar

perhaps the right thing to do is to expand union and find that there can be a + operation when x is number or string, but it seems that tsc did not do so.


try defining the type of return value


seems to be designed on purpose issues/29098

Menu