JavaScript was intended for writing short code snippets of just a few lines that were to be embedded in web pages. No one could foresee JavaScript becoming as popular as it is now or it being used to write applications with thousands of lines of code.
As much as JavaScript has grown and is now widely used in building applications, it is not a perfect language. Its humble beginnings and its initial intended use mean that JavaScript has some quirks that can make building large-scale applications a nightmare.
For instance, JavaScript won’t throw an error when you reference elements that do not exist in an object or when you multiply null with a numerical value.
To JavaScript, an empty string(“”) is equal to 0(zero) when the two are compared using an equality operator(==). Worse still, JavaScript won’t show you such errors in your code in development. You’ll only see the errors once you execute your program.
TypeScript, built on top of JavaScript, was thus developed to alleviate the challenges that arise when building applications with JavaScript. To achieve this, TypeScript does static type-checking as you write your code.
Static checking means detecting errors in your code without you having to run your code. Static type checking is thus checking for errors during development based on the type of values being operated on in the code.
TypeScript is a typed superset of JavaScript. Being a superset of JavaScript means that any valid JavaScript code is also valid TypeScript. Being typed means that TypeScript adds rules on how different data types can be used. TypeScript is also strongly typed, and you can’t work around the restrictions enforced by the type system.
TypeScript is a big milestone and a significant development in web development. TypeScript allows you to write more readable code that is easy to maintain. It also enforces good coding practices, and it helps developers catch and avoid errors when writing code.
TypeScript is more reliable and easy to refactor, which makes it ideal for building large-scale applications compared to JavaScript. With TypeScript being strongly typed, let us look at type conversion, its importance, and how TypeScript handles type conversions.
Type Conversion in TypeScript and its Importance
Type conversion is the process of converting a value from one data type to another, such as converting a string value to a number. Type conversion can be done implicitly, where the compiler automatically converts compatible data types during complications.
Type conversion can also be explicit, where the type conversion is explicitly required in the source code. This is often referred to as typecasting.
Type conversion is important because it allows developers to work with different data formats while still conforming to the expected data types in TypeScript. It also helps to ensure predictable outcomes from source codes.
As a developer, casting the types yourself helps you ensure your code still meets the types requirements of TypeScript. It makes your code more readable and understandable and helps prevent type-related errors.
Type conversions also help support data validations, and it helps TypeScript help you in development by providing all the built-in tools, such as autocompletion, which are associated with specific types.
A common use case for type conversion is with strings and numbers. When converting strings to numbers in TypeScript, to avoid errors in your code only converts numerical strings to numbers. That is, you can convert strings such as “1”, “235”, “5234.5” and so on. However, do not convert strings such as “hello” to a number
Let us look at the different ways of converting strings to numbers in TypeScript:
Type Assertion using ‘as’
When working with various data types in your TypeScript code, at times, you will have more information about the type of a value that TypeScript can’t know about. In such cases, you tell TypeScript what type a variable will be and don’t let the compiler infer the type. This is called type assertion.
Type assertion is done using the as keyword. To use type assertion to convert a string to a number, first set the type of the string to unknown. This is because, by default, TypeScript considers any conversion of type string to a number to be potentially a mistake. This is because neither string nor number sufficiently overlaps with the other. To convert a string to a number using as proceed as shown below:
/**
* set the type of numString to be unkown, otherwise,
* Typescript will infer numString to be a string value
*/
let numString: unknown = "23452";
// Type conversion using as - numString is converted to a number
// and assigned to the variable score
let score = numString as number;
console.log(score);
console.log(score * 35);
Output:
23452
820820
From the output, notice that the variable numString
was converted to a number and assigned to score. We then can do numerical computations such as multiplication with score because its value is a number
Type Assertion Using <>
Type assertion using <> can also be used to convert a string to a number. It works exactly like using the as keyword. The only difference in the implementation is the syntax, which is shown below:
let numString: unknown = "23452";
// Type assertion using <> to convert a string to a number
let score = <number>numString;
console.log(score);
console.log(score * 35);
Output:
23452
820820
The output is the same as using the as keyword. Again, remember not to use type assertion to convert strings that don’t have numerical values in them.
Using the Number Constructor
To convert a string to a number using the Number constructor pass in the string you want to convert into the Number constructor as shown in the code snippet below:
let numString = "23452"; // type inferred to string
let lives: string = "20"; // type annotated to string
// pass in string to Number constructor to convert to number
let score = Number(numString)
console.log(score / 17)
// pass in string to Number constructor to convert to number
let remainingLives = Number(lives);
console.log(remainingLives - 4)
Output:
1379.5294117647059
16
When using the Number constructor, you don’t have to set the type of the string to unknown. It works with string values that have been annotated or inferred to string. However, remember to pass in numerical strings such as “514”. If you pass in a string that can’t be converted to a number, NaN (Not-a-Number) will be returned.
Using the Unary plus (+) operator
The Unary plus (+) operator, which precedes its single operand, evaluates to the operand it precedes. For instance, +2 evaluates to the number 2, +542 evaluates to the number 542, and so on. However, if the operand is not a number, the unary plus (+) operator attempts to convert it into a number.
For instance, +”98″, will evaluate to98, and +”0″ will evaluate to the number 0. Therefore, we can use the unary plus (+) operator to convert strings to numbers. If you pass in a string that can’t be converted to a number, NaN is returned as shown below:
let numString1 = "23452";
let numString2 = "973.82"
let word = "hello"
// Using the Unary plus (+) to convert strings to numbers
let num1 = +numString1;
let num2 = +numString2;
let notNumber = +word;
console.log(`${num1} is a ${typeof num1}`);
console.log(`${num2} is a ${typeof num2}`);
console.log(notNumber);
Output:
23452 is a number
973.82 is a number
NaN
Using the unary plus (+) operator is a good way to convert strings to numbers as it is fast and does not do any additional operations on its operands.
Using parseInt() and parseFloat()
Just like in JavaScript, Typescript does not distinguish between integers and decimal numbers also known as floating point numbers. All are considered to be of type number. That said, the behaviors of parseInt() and parseFloat() differ slightly.
parseInt() takes in a string argument, parses it, and returns an integer equivalent according to the specified radix. parseFloat() takes in a string and parses it returning a floating point number.
For instance, if you pass in “897” to both parseInt() and parseFloat(), you’ll get back the number 897. However, if you pass in 897.75 to both parseInt() and parseFloat(), parseInt() will return 897 while parsefloat() will return 897.75.
Therefore, when converting numerical strings that don’t have a decimal place, use parseInt(), however, if the numerical string has decimal places, use parseFloat() as shown in the code below:
let numString1 = "897.75";
let numString2 = "724";
let word = "hello";
console.log("Parsing numerical strings with decimal numbers")
console.log(`Using parseInt -> ${parseInt(numString1)}`);
console.log(`Using parseFloat -> ${parseFloat(numString1)}`);
console.log("Parsing numerical strings with whole numbers")
console.log(`Using parseInt -> ${parseInt(numString2)}`);
console.log(`Using parseFloat -> ${parseFloat(numString2)}`);
console.log("Parsing strings that can't convert to number")
console.log(parseInt(word));
console.log(parseFloat(word));
Output:
Parsing numerical strings with decimal numbers
Using parseInt -> 897
Using parseFloat -> 897.75
Parsing numerical strings with whole numbers
Using parseInt -> 724
Using parseFloat -> 724
Parsing strings that can't convert to number
NaN
NaN
Conclusion
When working with string values, such as the result of API calls, you might want to convert them into numbers so that you can perform numerical computations on them. When such a need arises, consider the methods highlighted in the article for converting strings to numbers.
However, whenever you are converting strings to numbers, be careful because you might get NaN when you try to convert a string to a number.
To avoid such an error, ensure all the strings you want to convert to a number are numerical strings. You can also use an if statement to check for NaN to avoid errors in your code.
You may also explore top TypeScript libraries and runtime to know as a developer.
-
EditorNarendra Mohan Mittal is a senior editor at Geekflare. He is an experienced content manager with extensive experience in digital branding strategies.