Parse an integer safely in TypeScript
3 Parse a whole number safely
easyWrite a function that turns text into a whole number and deals with input that is not a number. Handle the failure rather than passing NaN on.
Stuck? Three hints, smallest first
- 1.
parseIntdoes not throw. It returnsNaN, which is of typenumber, so nothing warns you. - 2.
parseInt('12abc', 10)is12.Number('12abc')isNaN. Decide which you want. - 3. Either throw, or return a result object saying whether it worked. Show both.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
// Version one: throw on bad input.
function parseIntStrict(text: string): number {
// Number('') is 0, and so is Number(' '). Without this guard, an empty
// form field would quietly become a valid zero.
if (text.trim() === '') {
throw new SyntaxError('no number was given');
}
const n = Number(text); // stricter than parseInt
if (!Number.isInteger(n)) {
throw new SyntaxError(`"${text}" is not a whole number`);
}
return n;
}
// Version two: return the outcome instead of throwing, for bulk input.
type Parsed = { ok: true; value: number } | { ok: false; reason: string };
function parseIntSafe(text: string): Parsed {
try {
return { ok: true, value: parseIntStrict(text) };
} catch (err) {
return { ok: false, reason: err instanceof Error ? err.message : 'unknown' };
}
}
for (const input of ['42', ' 7 ', '12abc', 'nine', '2.5', '']) {
const r = parseIntSafe(input);
console.log(JSON.stringify(input), '->', r.ok ? r.value : r.reason);
}
// Two traps the strict version avoids:
const looseParse = parseInt('12abc', 10);
const emptyIsZero = Number('');
console.log('parseInt("12abc", 10) is', looseParse);
console.log('Number("") is', emptyIsZero, '-- not NaN');
test('a clean number', parseIntStrict('42'), 42);
test('surrounding spaces are fine', parseIntStrict(' 7 '), 7);
test('trailing letters are rejected', parseIntSafe('12abc').ok, false);
test('words are rejected', parseIntSafe('nine').ok, false);
test('fractions are rejected', parseIntSafe('2.5').ok, false);
test('empty text is rejected', parseIntSafe('').ok, false);
test('whitespace alone is rejected too', parseIntSafe(' ').ok, false);
test('but parseInt would have accepted 12abc', looseParse, 12);
test('and Number("") is a plausible-looking zero', emptyIsZero, 0);
Output
The last two assertions are the reason this exercise exists. parseInt('12abc', 10) quietly gives you 12, so a typo becomes a plausible number. Worse, Number('') is 0, not NaN, and so is Number(' ') — meaning an empty form field sails through Number.isInteger as a valid zero. That one caught me while writing this exercise, and only the assertion found it. Hence the trim() === '' guard before any conversion.