Type guard to check a number is odd in TypeScript
5 Is this number odd, and is it really a number?
fairWrite a function that reports whether a number is odd. Guard the input so that a value which is not a usable number is rejected rather than quietly giving a wrong answer.
Stuck? Three hints, smallest first
- 1. The type says
number, butNaNandInfinityare both numbers as far as the type system is concerned. - 2.
Number.isInteger(n)rules outNaN,Infinityand fractions in one call. - 3. Remember
-3 % 2is-1, not1, so compare with!== 0rather than=== 1.
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)}`)
);
}
function isOdd(n: number): boolean {
// The annotation does not stop NaN, Infinity or 2.5 getting in here,
// because all three are of type number.
if (!Number.isInteger(n)) {
throw new RangeError(`isOdd needs a whole number, got ${n}`);
}
// -3 % 2 is -1, so testing against 1 would call -3 even.
return n % 2 !== 0;
}
// A guard that reports instead of throwing, for when you have untrusted input.
function isUsableInteger(value: unknown): value is number {
return typeof value === 'number' && Number.isInteger(value);
}
console.log(isOdd(7), isOdd(8), isOdd(-3));
for (const candidate of [7, 2.5, NaN, 'nine']) {
console.log(candidate, 'usable?', isUsableInteger(candidate));
}
const refused: string[] = [];
for (const bad of [2.5, NaN, Infinity]) {
try { isOdd(bad); } catch (err) { refused.push((err as RangeError).message); }
}
test('7 is odd', isOdd(7), true);
test('8 is not', isOdd(8), false);
test('negative odd still odd', isOdd(-3), true);
test('guard accepts a whole number', isUsableInteger(7), true);
test('guard rejects a fraction', isUsableInteger(2.5), false);
test('guard rejects text', isUsableInteger('nine'), false);
test('three bad inputs were refused', refused.length, 3);
Output
The lesson is that n: number is a narrower promise than you might assume. NaN, Infinity and 2.5 all satisfy it. When a function only makes sense for whole numbers, say so at runtime with Number.isInteger; the type system cannot do it for you.