isDate
The isDate utility is a type guard that checks if a given value is a valid JavaScript Date object.
Implementation
View Source Code
ts
/**
* Determines if the passed value is a valid Date Object.
*
* @example
* ```ts
* isDate(new Date()); // true
* isDate(123); // false
* ```
*
* @param arg - The argument to be checked.
*
* @returns `true` if the value is a valid Date object, else `false`.
*/
export function isDate(arg: unknown): arg is Date {
return arg instanceof Date && !Number.isNaN(arg.getTime());
}
export const IS_DATE_ERROR_MSG = 'Expected a Date object';Features
- Isomorphic: Works in both Browser and Node.js.
- Type Guard: Automatically narrows types to
Datewithin conditional blocks. - Strict Check: Only returns
truefor actualDateinstances that are also valid (not "Invalid Date").
API
ts
function isDate(value: unknown): value is Date;Parameters
value: The value to check.
Returns
trueif the value is a validDateobject; otherwise,false.
Examples
Basic Usage
ts
import { isDate } from '@vielzeug/toolkit';
isDate(new Date()); // true
isDate(new Date('abc')); // false (Invalid Date)
isDate('2024-01-01'); // false (String, not Date object)
isDate(Date.now()); // false (Number, not Date object)Type Guarding
ts
import { isDate } from '@vielzeug/toolkit';
function format(val: unknown) {
if (isDate(val)) {
// val is narrowed to Date
return val.toISOString();
}
}Implementation Notes
- Returns
trueifvalue instanceof Dateand!isNaN(value.getTime()). - Throws nothing; safe for any input type.