isNumber
Checks if a value is a number (excluding NaN).
Implementation
View Source Code
ts
/**
* Determines if the passed value is a number.
*
* @example
* ```ts
* isNumber(123); // true
* isNumber('hello world'); // false
* ```
*
* @param arg - The argument to be checked.
*
* @returns `true` if the value is a number, else `false`.
*/
export function isNumber(arg: unknown): arg is number {
return typeof arg === 'number' && !Number.isNaN(arg);
}
export const IS_NUMBER_ERROR_MSG = 'Expected a number';Features
- Type Guard: Narrows
unknowntonumber - NaN Exclusion: Returns
falsefor NaN values - Isomorphic: Works in both Browser and Node.js
API
ts
function isNumber(value: unknown): value is number;Parameters
value: The value to check
Returns
trueif the value is a number (and not NaN),falseotherwise
Examples
Basic Usage
ts
import { isNumber } from '@vielzeug/toolkit';
isNumber(42); // true
isNumber(3.14); // true
isNumber(NaN); // false
isNumber('42'); // false
isNumber(Infinity); // trueType Guard Usage
ts
import { isNumber } from '@vielzeug/toolkit';
function calculate(value: unknown) {
if (isNumber(value)) {
// TypeScript knows value is number here
return value * 2;
}
return 0;
}Implementation Notes
- Explicitly excludes
NaN(sincetypeof NaN === 'number'in JavaScript) - Returns
trueforInfinityand-Infinity - Use for validation and type narrowing in TypeScript
See Also
- isString: Check if value is a string
- isPrimitive: Check if value is a primitive type
- isPositive: Check if number is positive
- isNegative: Check if number is negative
- typeOf: Get the type of any value