In TypeScript, converting a string to a number requires both runtime validation and compile-time type narrowing. Calling Number(value) returns NaN on invalid strings (and 0 on empty/whitespace strings), while TypeScript’s static type for Number(str) is still number—so returning number | null (or number | undefined) after guarding against NaN and blank strings keeps your types honest at runtime too.
1. Clean General-Purpose Float/Decimal Parser
Use Number(trimmed) after checking for non-empty text and Number.isFinite() so NaN, Infinity, and blank strings are rejected cleanly:
function parseNumber(input: string): number | null {
const trimmed = input.trim();
if (trimmed.length === 0) return null;
const parsed = Number(trimmed);
return Number.isFinite(parsed) ? parsed : null;
}
const price = parseNumber(" 19.95 "); // number | null -> 19.95
const invalid = parseNumber("abc"); // number | null -> null
const blank = parseNumber(" "); // number | null -> null
2. Strict Integer Parsing in TypeScript
When you only want whole base-10 integers—and want to reject "42px" or "3.14" rather than silently truncating—combine a strict regex check with Number.parseInt(trimmed, 10) and Number.isSafeInteger():
function parseStrictInt(input: string): number | null {
const trimmed = input.trim();
if (!/^[+-]?\d+$/.test(trimmed)) return null;
const parsed = Number.parseInt(trimmed, 10);
return Number.isSafeInteger(parsed) ? parsed : null;
}
const page = parseStrictInt("3"); // number | null -> 3
const withUnit = parseStrictInt("10px"); // number | null -> null
3. Common Traps to Avoid in TypeScript
- Using the unary plus (
+str) on untrusted strings:+""evaluates to0, and+"not-a-number"evaluates toNaNwhile still having typenumberin TypeScript. - Treating
NaNas a type guard:typeof NaNis"number"in JavaScript and TypeScript—always checkNumber.isFinite()orNumber.isNaN()explicitly. - Using
Numberfor large 64-bit integer IDs: Values aboveNumber.MAX_SAFE_INTEGER(9007199254740991) lose precision; parse those withBigInt(trimmed)instead when you need exact large integers.
TL;DR: Trim first, reject empty strings, convert with Number(trimmed) (or Number.parseInt(trimmed, 10) for strict integers), check Number.isFinite() / Number.isSafeInteger(), and return number | null so TypeScript forces you to handle invalid inputs.
Are you parsing form/query inputs into floats or strict integers, or handling large numeric IDs beyond Number.MAX_SAFE_INTEGER?
