Use Number(text) (or the shorter +text). The result is typed number, and text that isn't a number as a whole gives NaN, which is a number too, so check it with Number.isFinite(). Don't write text as number: an assertion converts nothing, and TypeScript rejects it with TS2352.
At runtime TypeScript is JavaScript, so the conversion functions are the JavaScript ones: Number(), unary +, parseInt and parseFloat. The JavaScript version of this page covers every edge case of how they parse, including BigInt. This page is about what the types add: the error you get when you try to cast instead of convert, the signatures that make parseInt(3.7) and isNaN("abc") compile errors, and how to type a parser so callers can't forget that the input might not have been a number.
Every example is written to pass with strict on, as in most projects, though this page's compiler runs without it. Each example runs on this page: hit Run, then edit the code and run it again.
1Number() and unary +Recommended
Number(text) converts the entire string: surrounding whitespace, a sign, decimals and exponents are fine, and anything else gives NaN. Unary +text runs the same conversion. Both are typed number, so the checker is happy from then on. Two things it can't do for you: tell a real number from NaN, and object to the input, because Number is declared to take any.
// Number() converts the whole string, and its result is typed number function toNumber(text: string): number { return Number(text); } const text = "42"; const n = toNumber(text); console.log(n, typeof n); console.log(n + 8); // real arithmetic console.log(text + 8); // text is still a string: "+" concatenates // Unary + runs the same conversion, also typed number const qty: number = +"3.5"; console.log(qty * 2); console.log(Number("3.14"), Number("-7"), Number("1e3"), Number(" 12 ")); // NaN is a number too, so the type cannot tell you the conversion failed const bad: number = Number("42px"); console.log(bad, typeof bad, Number.isNaN(bad)); // Number() accepts any value, so a missing env var becomes NaN, not an error const env: NodeJS.ProcessEnv = { PORT: "8080" }; console.log(Number(env.PORT), Number(env.HOST)); console.log(Number(env.HOST ?? "3000")); // default before converting
Output
Prints 42 number, then 50, then 428: the unconverted text + 8 compiles because adding a number to a string is legal, and its type is string, so the checker only catches it once you pass the result somewhere that wants a number. +"3.5" doubles to 7. The failed conversion prints NaN number true: same type as a good result, so test it (section 4). A missing environment variable becomes NaN without a type error, and putting the default before the conversion gives 3000.
2Why "as number" doesn’t convert
The most common TypeScript attempt is a cast: text as number or the older <number>text. Both stop the build with error TS2352: Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. The error is right. A type assertion only changes what the checker believes; it emits no code. Follow the hint and write as unknown as number, and it compiles, but the value is still a string.
const text: string = "42"; // "text as number" is rejected (TS2352). Going through unknown compiles... const n = text as unknown as number; // ...but nothing was converted: an assertion only changes what the checker believes console.log(typeof n); console.log(n + 1); // typed number, prints a concatenation console.log(n === 42); try { console.log(n.toFixed(2)); } catch (err) { console.log((err as Error).message); } // The same happens when JSON.parse output is asserted to a type interface Item { name: string; price: number; } const item = JSON.parse('{"name": "pen", "price": "1.5"}') as Item; console.log(item.price + 1, typeof item.price); // The fix is a real conversion const m = Number(text); console.log(typeof m, m + 1, m.toFixed(2)); const checked: Item = { ...item, price: Number(item.price) }; console.log(checked.price + 1);
Output
The asserted value prints string, n + 1 is 421 although its type says number, n === 42 is false, and n.toFixed(2) fails at runtime with n.toFixed is not a function. Asserting JSON.parse output to an interface is the same trap in disguise: the price string gives 1.51 string. A real Number() fixes both (number 43 42.00 and 2.5). For checking parsed JSON field by field, see parse JSON into a typed object.
3parseInt() and parseFloat(): read the number at the start
parseInt and parseFloat read as many characters as make a number and stop at the first one that doesn't fit, so they suit text like "42px" and not validation. Always pass parseInt its radix. TypeScript adds one guard: both are declared to take a string, so parseInt(3.7, 10), the old trick for dropping decimals, fails with error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. Use Math.trunc for that.
// parseInt and parseFloat read the number at the start and stop at the first bad character console.log(parseInt("42px", 10)); console.log(parseFloat("3.99 USD")); console.log(parseInt("3.99", 10)); // stops at the dot, no rounding console.log(parseInt("abc", 10)); // nothing to read at all // Always pass the radix: without it "0x" switches to hex console.log(parseInt("0x1F"), parseInt("0x1F", 10)); console.log(parseInt("ff", 16), parseInt("1010", 2)); // Both take a string, so parseInt(3.7, 10) does not compile (TS2345). // To drop the decimals of a number, use Math.trunc const price = 3.7; console.log(Math.trunc(price), Math.round(price), Math.floor(-price)); // The checker does not catch map passing the index as the radix const parts = ["10", "10", "10"]; console.log(parts.map(parseInt)); console.log(parts.map(Number)); console.log(parts.map((s) => parseInt(s, 10)));
Output
The partial reads print 42, 3.99, 3 and NaN. Without a radix "0x1F" is 31, with radix 10 it is 0. Math.trunc, Math.round and Math.floor (of the negated number) give 3 4 -4. The last three lines show what the checker misses: parts.map(parseInt) compiles, because map's index fits the optional radix parameter, and prints [ 10, NaN, 2 ]. map(Number) or an arrow function with an explicit radix gives [ 10, 10, 10 ].
4Check the result: return number | null
None of these functions throw, so validation means checking the result. The JavaScript habit isNaN(text) doesn't compile here: the global isNaN is declared to take a number, and a string argument gives error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. Convert first, then test with Number.isFinite, which takes any value. Wrap that in a function that returns number | null, and the type itself reminds every caller that the input may not have been a number.
// Return number | null so every caller has to handle "not a number" function parseNumber(text: string): number | null { if (text.trim() === "") return null; // Number("") would be 0 const n = Number(text); return Number.isFinite(n) ? n : null; // rejects NaN and Infinity } for (const s of ["42", "-3.5", " 7 ", "1e3", "", " ", "12px", "Infinity"]) { console.log(JSON.stringify(s).padEnd(10), parseNumber(s)); } // Check the result before using it (strict mode insists) const qty = parseNumber("12"); if (qty === null) { console.log("not a number"); } else { console.log(qty * 2); } console.log((parseNumber("abc") ?? 0) + 1); // or fall back to a default // For input of unknown type, narrow with typeof first function toInt(value: unknown): number | null { if (typeof value === "number") return Number.isInteger(value) ? value : null; if (typeof value !== "string") return null; const n = parseNumber(value); return n !== null && Number.isInteger(n) ? n : null; } console.log(toInt("8"), toInt(8), toInt("2.5"), toInt(true), toInt(undefined));
Output
parseNumber returns 42, -3.5, 7 and 1000, and null for the blank strings, "12px" and "Infinity". The checked result doubles to 24, the default gives 1, and toInt prints 8 8 null null null. With strict on, skipping the check is a compile error: qty * 2 gives error TS18047: 'qty' is possibly 'null'. and const port: number = parseNumber("8080") gives error TS2322: Type 'number | null' is not assignable to type 'number'. More on those checks in check for null or undefined.
5The other way: number to string
Casting fails in this direction too: n as string is the same TS2352 error with the types swapped, and assigning a number where a string is expected gives error TS2322: Type 'number' is not assignable to type 'string'. Convert instead. String(n), n.toString() and a template literal all work; toFixed, toString(radix) and toLocaleString format while they convert.
const n = 42; // Four ways to get the string "42" const a: string = String(n); const b: string = n.toString(); const c: string = `${n}`; const d: string = "" + n; console.log(JSON.stringify([a, b, c, d])); // Format while converting const price = 1234.5; console.log(price.toFixed(2)); console.log((255).toString(16), (5).toString(2).padStart(8, "0")); console.log(price.toLocaleString("en-US", { style: "currency", currency: "USD" })); console.log(price.toLocaleString("de-DE")); // String() turns null and undefined into text; ?. and ?? let you choose const values: (number | null | undefined)[] = [7, null, undefined]; console.log(values.map(String)); console.log(values.map((v) => v?.toString() ?? ""));
Output
All four give "42". The formatted lines print 1234.50, ff 00000101, $1,234.50 and the German 1.234,5. The last two lines matter when the number may be missing: String happily produces 'null' and 'undefined' as text, while v?.toString() ?? "" lets you pick what a missing value becomes. Drop the ?. and, with strict on, v.toString() fails with error TS18049: 'v' is possibly 'null' or 'undefined'.
6Which should you use?
| Method | Type of the result | On "42px" | Best for |
|---|---|---|---|
| Number(s) | number (may be NaN) | NaN (rejects) | Converting a whole string: the default |
| +s | number (may be NaN) | NaN (rejects) | Same as Number(), shorter |
| parseInt(s, 10) | number (may be NaN) | 42 (partial read) | An integer at the start of text; other radixes |
| parseFloat(s) | number (may be NaN) | 42 (partial read) | A decimal at the start of text, like "3.99 USD" |
| parseNumber(s): number | null | number | null | null | User input: callers must handle the failure |
| s as unknown as number | number, but still a string | stays "42px" | Nothing: it converts nothing |
Frequently asked questions
Why does "as number" not convert a string to a number?
A type assertion is erased when TypeScript compiles, so it never runs any code. text as number is rejected with TS2352 because string and number do not overlap, and text as unknown as number compiles but leaves the string in place: typeof still prints string and n + 1 concatenates. Use Number(text) or +text to convert.
Why is isNaN("abc") a type error in TypeScript?
The global isNaN is declared as isNaN(number: number): boolean, so a string argument fails with error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. The JavaScript trick of passing a string relied on isNaN converting it, which also made blank strings count as numbers. Convert first and check the number: Number.isFinite(Number(text)), after rejecting blank strings.
How do I convert a decimal string to an integer?
Convert with Number, then choose the rounding: Math.trunc(Number("-3.99")) is -3, and Math.round, Math.floor and Math.ceil round the other ways. parseInt("-3.99", 10) also gives -3 because it stops at the dot. Passing a number to parseInt to drop decimals does not compile in TypeScript (TS2345), which is a good thing: that trick breaks on small and very large numbers.
How do I convert a string to a BigInt in TypeScript?
Use BigInt(text), typed bigint. Past Number.MAX_SAFE_INTEGER a number rounds: Number("9007199254740993") is 9007199254740992, while BigInt("9007199254740993") + 1n is 9007199254740994n. TypeScript refuses to mix the two types, so big + 1 fails with error TS2365: Operator '+' cannot be applied to types 'bigint' and '1'. Write big + 1n, or convert one side explicitly.
Is there a TypeScript type for a string that contains a number?
Yes, the template literal type ${number}. A variable of that type accepts string literals that read as numbers, such as "42" or "1e3", and the checker rejects "abc" with a TS2322 error. It only checks literals written in the code; a string that arrives at runtime is plain string and still needs Number() and a check.
Run it yourself
Open any of these in the full TypeScript editor to tweak, run and share.
TypeScript playground