Solve - Adding numbers concatenates them in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 8, 2022

banner

Check out my new book

Solve - Adding numbers concatenates them in TypeScript #

If adding numbers in TypeScript concatenates them, then one of the values has a type of string and implicitly converts the rest to strings. To solve this, use the Number() function to convert the string to a number before the addition.

Here is an example of how this behavior is caused.

index.ts
const num1 = 50; // 👇️ this is a string const num2 = '50'; const result = num1 + num2; console.log(result); // 👉️ "5050"

The num2 variable in the example stores a string of 50.

When you add a number to a string in JavaScript (and TypeScript), the number gets implicitly converted to a string and the two strings are concatenated.

You can check the type of a specific value by using the typeof operator.

index.ts
const num1 = 50; console.log(typeof num1); // 👉️ "number" // 👇️ this is a string const num2 = '50'; console.log(typeof num2); // 👉️ "string"

To solve this issue, use the Number() function to convert the string to a number before the addition.

index.ts
const num1 = 50; const num2 = '50'; const result = num1 + Number(num2); console.log(result); // 👉️ 100

We passed the num2 variable to the Number function and converted it to a number before adding the 2 numbers.

You have to make sure that all of the values you are adding have a type of number, because if even one of the values is a string, it implicitly converts all of the numbers to strings and concatenates them.

TypeScript can help you track down issues like this one if you explicitly type the variables in the expression.

index.ts
// ⛔️ Type 'string' is not assignable // to type 'number'.ts(2322) const num2: number = '50';

We've set the num2 variable to have a type of number, so if it gets assigned a string, the type checker throws an error.

You can convert a string that stores a valid number to a number, by passing it to the Number() function.

index.ts
const num2 = Number('50'); console.log(typeof num2); // 👉️ "number"

Note that if the string you are converting to a number is not a valid number, you will get an NaN (not a number) value back.

index.ts
const num1 = 50; const num2 = Number('hello'); console.log(num2); // 👉️ NaN console.log(num1 + num2); // 👉️ NaN
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.