With TypeScript, comes types. Things are stricter than the implicit conversion you’ll see in JavaScript. This means you’ll need to know how to safely convert between types. In this article, I’ll cover options for converting between the three primitive types you’re likely to be converting between the most often — strings, numbers and booleans.
A Quick Note on Truthiness
One important thing to discuss here is what it means to convert from something to a boolean. Converting a number to a boolean for example, if we say 0 is false and 1 is true, that makes sense right? But those aren’t the only numbers — what about 3 — true or false? Or -1, true or false? TypeScript, and JavaScript handle this with truthiness. A truthy value is anything that is considered true when treated as a boolean. It’s easier to go through the list of values that are falsy, which are:
Everything else is truthy.
So when converting values to boolean, it’s important to make a distinction between whether you want whatever your definition of true and false are for your context, and native TypeScript/JavaScript truthiness.
Strings
Strings to Numbers
There are two main ways to convert strings to numbers in TypeScript, parseFloat and the Number constructor.
Using parseFloat
“parseFloat” is a built-in function that converts a string to a number. It scans the string from left to right until it encounters a character that cannot be converted to a number. It then returns the numeric value parsed up to that point.
Here’s how you can use “parseFloat()” in TypeScript:
function stringToNumber(str: string) {
return parseFloat(str);
}
console.log(stringToNumber('10')); //10
console.log(stringToNumber('10 and 11')); //10
console.log(stringToNumber('ten and 11')); //NaN
console.log(stringToNumber('ten')); //NaN
So:
- If we input a string that represents a number, we get out a number
- If we input a string that starts with a number, we get just that number
- If we input a string that doesn’t start with a number, we get NaN
- If we input a string with no number, we get NaN
The NaN part is something to take note of. If you’re not familiar with NaN — it stands for Not A Number. It’s a special case that represents as you’d guess, anything that isn’t a number, for example 0/0, or the result of one of the number conversion functions failing.
One important thing is that NaN === NaN is false, which means this is false:
console.log(Number('ten') === Number('ten')); //false
So if your conversion silently fails and you compare the results, they will never be equal.
Using Number()
The Number() constructor in TypeScript can be used to explicitly convert a string to a number. It tries to convert the argument passed to it into a number. If the argument cannot be converted into a valid number, it returns NaN. Let’s take a look:
function stringToNumber(str: string) {
return Number(str);
}
console.log(stringToNumber('10')); //10
console.log(stringToNumber('10 and 11')); //NaN
console.log(stringToNumber('ten and 11')); //NaN
console.log(stringToNumber('ten')); //NaN
Pretty similar to “parseFloat()”.The big difference is in the second case. “parseFloat” will scan the string from left to right and find the number 10, whereas Number will see that the whole thing is not a valid number, so it will return NaN
Strings to Booleans
There are a few ways to convert a string to a boolean, depending on what you want to consider true or false. The simplest way is just checking whether a string is truthy or not, which can be done with the Boolean() constructor:
function stringToBoolean(str: string) {
return Boolean(str);
}
console.log(stringToBoolean('true')); //true
console.log(stringToBoolean('True')); //true
console.log(stringToBoolean('false')); //true
console.log(stringToBoolean('False')); //true
console.log(stringToBoolean('')); //false
console.log(stringToBoolean('Just a string')); //true
If the string is truthy, the string returns true. This means any string that isn’t an empty string.
This might not be useful depending on your use case. If you’re just checking if the string is empty then this works, but in other cases you might not want “false” or “False” to be considered truthy.
The simplest way is just checking if the string is equal to “true”:
function stringToBoolean(str: string) {
return str === 'true';
}
console.log(stringToBoolean('true')); //true
console.log(stringToBoolean('True')); //false
console.log(stringToBoolean('false')); //false
console.log(stringToBoolean('False')); //false
console.log(stringToBoolean('')); //false
console.log(stringToBoolean('Just a string')); //false
Or for a case-insensitive version:
function stringToBoolean(str: string) {
return str.toLowerCase() === 'true';
}
console.log(stringToBoolean('true')); //true
console.log(stringToBoolean('True')); //true
console.log(stringToBoolean('false')); //false
console.log(stringToBoolean('False')); //false
console.log(stringToBoolean('')); //false
console.log(stringToBoolean('Just a string')); //false
Numbers
Numbers to Strings
The easiest way to convert a number to a string in TypeScript is through the .toString() method:
function numberToString(num: number) {
return num.toString();
}
console.log(numberToString(42)); //"42"
console.log(numberToString(-1)); //"1"
console.log(numberToString(NaN)); //"NaN"
One neat feature of this function is that it lets you choose the base/radix of the string, which lets you do things like convert a number to binary:
function numberToString(num: number) {
return num.toString(2);
}
console.log(numberToString(42)); //"101010"
console.log(numberToString(-10)); //"-1010"
console.log(numberToString(NaN)); //"NaN"
Or convert a number to hexadecimal:
function numberToString(num: number) {
return num.toString(16);
}
console.log(numberToString(12648243)); //"c0ff33"
console.log(numberToString(-10)); //"-a"
console.log(numberToString(NaN)); //"NaN"
That covers converting a plain number to a plain string, but if you’re dealing with something like percentages there are ways to
Numbers to Booleans
Like strings, the “Boolean()” constructor is the easiest way to convert a number to a boolean:
function numberToBoolean(num: number) {
return Boolean(num);
}
console.log(numberToBoolean(-1)); //true
console.log(numberToBoolean(0)); //false
console.log(numberToBoolean(1)); //true
console.log(numberToBoolean(NaN)); //false
Any numbers that aren’t NaN or 0 are truthy.
Booleans
Booleans are a little more straightforward, since there are only two possible values, and they both convert easily to strings/numbers.
Booleans to Strings
Booleans contain a handy “toString()” method for converting them to strings:
function booleanToString(bool: boolean) {
return bool.toString();
}
console.log(booleanToString(true)); //"true"
console.log(booleanToString(false)); //"false"
True to “true”, false to “false”.
Booleans to Numbers
The “Number” constructor is the easiest way to convert a boolean to a number. “parseFloat” won’t work here as it only accepts strings.
console.log(booleanToNumber(true)); //1
console.log(booleanToNumber(false)); //0
As you might expect, true gets converted to 1, and false gets converted to 0.
Conclusion
Thanks for reading! Hopefully, with this article, you were able to get a good grasp of how to convert between primitives in TypeScript. If you liked this article, why not check out more of my posts.
Originally published at https://www.omarileon.me.
Top comments (0)