How to Cast a Number to String in TypeScript

Muhammad Ibrahim Alvi Feb 02, 2024
  1. Type Casting in TypeScript
  2. Casting a Number to String Using Template Literals in TypeScript
  3. Casting a Number to String Using toString() in TypeScript
  4. Casting a Number to String Using String Constructor in TypeScript
How to Cast a Number to String in TypeScript

This tutorial provides guidelines about type casting and how casting a number to a string can be done using different methods in TypeScript.

Type Casting in TypeScript

Type casting means changing an expression from one data type to another.

TypeScript is compiled to JavaScript and behaves differently; it does not give two hoots about the types defined by you, and there is no runtime to enforce types during the execution.

Example:

let data:string = '123';
console.log("Type of Data before Type Cast==>",typeof data);
console.log("Type of Data after Type Cast==>",typeof Number(data));

Output:

Type Casting in TypeScript

The variable data is assigned with a type of string by default. After using the Number constructor, we see the conversion of string data type to a number data type.

Casting a Number to String Using Template Literals in TypeScript

Use the Template Literals, which uses the backticks(`) for conversion.

Example:

let pageNumber:number = 123;
let castTemp:string = `${pageNumber}`;
console.log("The Data Type of castTemp is:",typeof castTemp);

Output:

Casting a Number to String Using Template Literals

Casting a Number to String Using toString() in TypeScript

The toString() method is a defined method available in TypeScript, and it will throw an error when the applied variable is null or undefined.

Example:

let pageNumber:number = 123;
let castTemp:string = pageNumber.toString();
console.log("The Data Type of castTemp is:",typeof castTemp);

Output:

Casting a Number to String Using toString()

Casting a Number to String Using String Constructor in TypeScript

One of the easier ways of converting a number to a string is using a String Constructor. This does not cast a number to string but converts it to a string.

Example:

let pageNumber:number = 123;
let castTemp:string = String(pageNumber);
console.log("The Data Type of castTemp is:",typeof castTemp);

Output:

Casting a Number to String Using String Constructor

Muhammad Ibrahim Alvi avatar Muhammad Ibrahim Alvi avatar

Ibrahim is a Full Stack developer working as a Software Engineer in a reputable international organization. He has work experience in technologies stack like MERN and Spring Boot. He is an enthusiastic JavaScript lover who loves to provide and share research-based solutions to problems. He loves problem-solving and loves to write solutions of those problems with implemented solutions.

LinkedIn

Related Article - TypeScript Casting