Concatenate a String and a Number in TypeScript

avatar

Borislav Hadzhiev

Tue Mar 08 20222 min read

banner

Photo by Larisa Birta

Concatenate a String and a Number in TypeScript #

Use the addition operator to concatenate a string and a number in TypeScript, e.g. str + num. The result will have a type of string, so make sure the type of the value to which it is assigned is either string or a union containing the string type, e.g. string | number.

index.ts
const num = 5; const str = '0'; // ✅ Using addition operator const result1 = str + num; console.log(result1); // 👉️ "05" // ✅ using template literal const result2 = `${str}${num}`; console.log(result2); // 👉️ "05"

The first example shows how to concatenate a string and a number by using the addition operator (+).

The result of concatenating a string to a number is a value that has a type of string.

index.ts
const num = 5; const str = '0'; // 👇️ const result1: string const result1 = str + num;

You would get an error if you try to assign the result to a value that expects a different type.

index.ts
const num = 5; const str = '0'; // 👇️ let result1: number let result1 = 50; // ⛔️ Error: Type 'string' is not // assignable to type 'number'.ts(2322) result1 = str + num;

The result1 variable has a type of number, so when we can't assign the result of concatenating a string and a number to it because it has a type of string.

If you are in a similar situation, use a union type that covers the number and string types.

index.ts
const num = 5; const str = '0'; // 👇️ let result1: number | string let result1: number | string = 50; result1 = str + num; console.log(result1); // 👉️ "05"

When writing TypeScript code, we have to make sure that the values on the left and right-hand side of the assignment have compatible types, otherwise the type checker throws an error.

You can also concatenate a string to a number by using a template literal.

index.ts
const num = 5; const str = '0'; const result2 = `${str}${num}`; console.log(result2); // 👉️ "05"

The dollar sign and curly braces syntax ${} allows us to evaluate an expression.

You can imagine that the str and num placeholders get replaced with the actual values.

A template literal is basically a string that allows us to interpolate variables and use logic via the dollar sign curly braces syntax.

index.ts
const name = 'James'; console.log(`Hello ${name}`); // 👉️ "Hello James"

Note that template literals use backticks ``, not single quotes.

The type of a template literal is always going to be a string, so you have to make sure to only assign it to variables of a compatible type.

Use the search field on my Home Page to filter through my more than 1,000 articles.