In this article, we will learn how to do type conversion in Typescript. So are you working on Typescript and now want to convert a value from string to number? Or want to convert a number to string in Typescript? Well, then read through this article to learn how to do that!
So here is the thing. You have a Typescript value stored in a variable and you want to use that. But the thing is that, you can not use it as is. Why? Because this number is stored as a string type. But you want to use it as a number. So how can we do that?
That is when the Typescript type conversion comes to your rescue! Using the Typescript type conversion, you can turn that variable’s value from a string to a number!
Sounds great! Right? But then how do we do that in our code? To learn that, take a look at the example code given below:
Example Of Type Conversion from a String to Number
let myStringOfNum: string = "10"; let myNumber: number = Number(myStringOfNum); console.log(typeof myStringOfNum); console.log(typeof myNumber);
So if you look at the above code, we have a variable called myStringOfNum that holds a string that reads “10”. But we want that string to be used as a number. So what do we do for that? We use Type Conversions!
So in Line 2, we declared another variable called myNumber. But this time, this variable is of type number. What we do next is that we will take the value of the vairable myStringOfNum and convert its type to Number. We do that by using the typecast Number(). The resulting value is then assigned to our variable myNumber.
So in that case, our console output will look like this:
Example Of Type Conversion from a Number to String
In a similar way, we can convert a number to string in Typescript. So when we take a look at this code:
let myNumber: number = 10 let myString: string = String(number) console.log(typeof myNumber); console.log(typeof myString);
What do you think how to output will look like? I think your guess will be:
So in summary, we can convert a number to string or a string to number using Typescript’s Type conversion feature. I guess it could not have been any more simpler than this. What do you guys think? It is, Right?