Solved- Adding two numbers concatenating them in TypeScript
July 12, 2022
Adding two numbers concatenating them in TypeScript:
This is a common error in TypeScript. If you are trying to add two numbers, it concatenates the numbers. The common reason for this issue is that one of the numbers is not a number. If it is a string, it will concatenate the other number to this string. Or if both numbers are strings, it will concatenate them.
Example program with this error:
Let’s take a look at the below example:
function getSum(first: any, second: any) {
return first + second;
}
console.log(getSum(10, 20));
console.log(getSum("10", 20));
In this example, getSum method takes two parameters. Both of these parameters are of type any. It returns the value of first + second.
For the first example, this method is called with two numbers. For the second example, it is called with one string and one number.
If you run this program, it will print:
30
1020
For the first example, it returns 30, and for the second example, it returns 1020. It concatenates the values in the second example.
There are two issues with this program:
- The parameters are any type. So, this function will not throw any compile-time error if we pass numbers or strings.
- It is using + to add the values of the parameters. But, since it can accept any type, it will concatenate or add the values.
Solution 1: By using union type:
One way to fix this issue is to use union type. Instead of any, we can use number | string i.e. it can accept number or string values. If it is a string, we can check it by using typeof and convert it to a number using Number.
function getSum(first: number | string, second: number | string) {
if (typeof first === "string") {
first = Number(first);
}
if (typeof second === "string") {
second = Number(second);
}
return first + second;
}
console.log(getSum(10, 20));
console.log(getSum("10", 20));
It will print 30 for both.
Solution 2: By using + operator:
We can also use the + operator to convert a string to number. It will look as like below:
function getSum(first: number | string, second: number | string) {
if (typeof first === "string") {
first = +first;
}
if (typeof second === "string") {
second = +second;
}
return first + second;
}
console.log(getSum(10, 20));
console.log(getSum("10", 20));
It will also print the same result.