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 TimeWithUnitDescription
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
| Parameter | Type | Required | Description |
|---|---|---|---|
value | unknown | Yes | Value to check |
Returns
boolean-trueif value is a valid time string,falseotherwise
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
| Unit | Variants |
|---|---|
| Year | y, yr, yrs, year, years |
| Month | mo, month, months |
| Week | w, week, weeks |
| Day | d, day, days |
| Hour | h, hr, hrs, hour, hours |
| Minute | m, min, mins, minute, minutes |
| Second | s, sec, secs, second, seconds |
| Millisecond | ms, msec, msecs, millisecond, milliseconds |
Usage Examples
playground.ts
Related
parseMSec- Parse time strings to milliseconds/seconds
Last updated: Fri, May 22, 2026 07:46:19AM (Coordinated Universal Time)
