How to convert a string to number in TypeScript?
In TypeScript, you can convert a string to a number using built-in JavaScript methods like Number(), parseInt(), or parseFloat(). TypeScript essentially compiles to JavaScript, so you can use the same approaches you’d use in plain JS, with the bonus of TypeScript’s type checks. Below are the most common techniques:
1. Number() Constructor
const str: string = "123"; const num: number = Number(str);
Number(str)attempts to parse the entire string as a decimal number.- If the conversion fails (e.g., the string isn’t numeric), it returns
NaN.
Example with Failing Conversion
const str2: string = "abc"; const result: number = Number(str2); // NaN
2. parseInt() and parseFloat()
const intStr: string = "42px"; const floatStr: string = "3.14something"; const intVal: number = parseInt(intStr, 10); // 42 const floatVal: number = parseFloat(floatStr); // 3.14
parseInt()reads an integer from the start of the string, ignoring trailing characters that aren’t part of a valid integer.parseFloat()reads a floating-point number similarly.- For
parseInt(), always specify the radix (e.g., 10 for decimal) to avoid browser-specific defaults for strings starting with0or0x.
3. Unary + Operator
In JavaScript/TypeScript, prefixing a string with the unary plus (+) attempts to convert it to a number:
const str: string = "456"; const num: number = +str; // 456 (number)
- This is syntactic sugar for
Number(str).
4. Using the TypeScript Non-Null Assertion Carefully
Sometimes you’ll see code like this:
const str: string | null = "789"; const num: number = +str!; // Using '!'
- The
!operator just tells TypeScript “this isn’tnullorundefined, trust me.” It doesn’t actually convert types. The+does the numeric conversion. - Use this carefully, only if you’re sure
stris nevernull.
5. Handling Invalid Conversions
All these methods return NaN if the string can’t be converted to a valid number. You can check with isNaN() or Number.isNaN() if needed:
const val = Number("oops"); // NaN if (Number.isNaN(val)) { console.log("Conversion failed!"); }
6. Comparison & Best Practices
Number(str): Good for a full conversion to a number. ReturnsNaNfor invalid input.parseInt(),parseFloat(): Good if you only want the initial numeric part of a string (like"42px"→42).- Unary
+: Concise, but can be less readable if you’re not familiar with the pattern. - Error-Handling: Always consider how you handle
NaN. - TypeScript: Remember that at runtime, TypeScript is just JavaScript—choose whichever JavaScript method best suits your scenario.
Bonus: Strengthen Your JavaScript (and TypeScript) Foundations
For a deeper understanding of JavaScript fundamentals—which TypeScript builds upon—check out:
Grokking JavaScript Fundamentals
- This course covers core JS concepts like closures, prototypes, async/await, and more, which are crucial for writing robust, type-safe code in TypeScript.
Summary:
Number(str)or+strif you want a straightforward numeric conversion.parseInt(str, 10)orparseFloat(str)if you want to parse partial numeric values at the start of the string (e.g.,"42px"→42).- Always handle potential
NaNresults for malformed strings or non-numeric input.
CONTRIBUTOR
TechGrind