Toolbox-XToolbox-X

Check Time with Unit

Check whether the provided value is a valid time string with supported units.

isTimeWithUnit

Type guard that checks if a value is a valid time string with supported units.

Function Signature

isTimeWithUnit(value: unknown): value is TimeWithUnit

Description

Checks whether a given value matches the pattern for time duration strings (e.g., "30s", "2h", "1.5 days"). Returns true for valid time strings and narrows TypeScript type to TimeWithUnit.

Parameters

ParameterTypeRequiredDescription
valueunknownYesValue to check

Returns

  • boolean - true if value is a valid time string, false otherwise

Type Guard Behavior

When this function returns true, TypeScript narrows the type to TimeWithUnit:

const input: unknown = getUserInput();
if (isTimeWithUnit(input)) {
  // input is now typed as TimeWithUnit
  const ms = parseMSec(input); // Type-safe
}

Supported Formats

Valid examples:

  • "30s", "2h", "1.5d"
  • "1 hour", "2 weeks", "500 milliseconds"
  • "1H", "2HOURS", "3Min" (case-insensitive)
  • "-5m", "+2.5h" (sign optional)
  • All combinations from TIME_UNIT_VARIANTS

Invalid examples:

  • "30" (no unit)
  • "s" (no number)
  • "30 unknown" (invalid unit)
  • Non-string values

Supported Units

UnitVariants
Yeary, yr, yrs, year, years
Monthmo, month, months
Weekw, week, weeks
Dayd, day, days
Hourh, hr, hrs, hour, hours
Minutem, min, mins, minute, minutes
Seconds, sec, secs, second, seconds
Millisecondms, msec, msecs, millisecond, milliseconds

Usage Examples

playground.ts
  • parseMSec - Parse time strings to milliseconds/seconds

Last updated: Fri, May 22, 2026 07:46:19AM (Coordinated Universal Time)

On this page