Skip to content

isNumber function ​

Checks whether a value is a number other than NaN. Infinities pass: use isFiniteNumber to exclude them.

ts
import { isNumber } from 'utils';

Signature ​

ts
export function isNumber(value: unknown): value is number

Parameters ​

NameDescription
valueThe value to check.

Returns ​

true for a number that is not NaN.

Example ​

ts
isNumber(Infinity); // true
isNumber(NaN); // false

Tests ​

Line coverage: 100 %.

  • ✅ checks 0 as true
  • ✅ checks -1.5 as true
  • ✅ checks Infinity as true
  • ✅ checks NaN as false
  • ✅ checks 1 as false
  • ✅ checks null as false

Source ​

src/guard/is-number.ts (on GitHub)

Source code
ts
/**
 * Checks whether a value is a number other than `NaN`. Infinities pass: use `isFiniteNumber` to exclude them.
 *
 * @param value - The value to check.
 * @returns `true` for a number that is not `NaN`.
 * @example
 * isNumber(Infinity); // true
 * isNumber(NaN); // false
 */
export function isNumber(value: unknown): value is number {
  return typeof value === 'number' && !Number.isNaN(value);
}
Test file
ts
import { isNumber } from './is-number';

describe(isNumber, () => {
  it.for([
    [0, true],
    [-1.5, true],
    [Infinity, true],
    [NaN, false],
    ['1', false],
    [null, false],
  ] as const)('checks %s as %s', ([value, expected]) => {
    expect(isNumber(value)).toBe(expected);
  });
});

Keywords: is, number, guards, function

Generated from the JSDoc of the sources.