Typed Duration
A Zero-dependency typed duration library for JavaScript/TypeScript. Express and convert time durations with type-safety.
This library uses Value Object Typing to allow you to express time durations in a type-safe way, and perform conversion between different units.
Use
Install the library to your project:
npm i typed-duration
Use
Consider the following code:
setTimeout(doSomething, 1000)
It's pretty clear that these are milliseconds, because you know the API. Typically, developers might do something like:
setTimeout(doSomething, 5 * 60 * 1000)
With this library, you can do this:
import { Duration } from 'typed-duration'
const { milliseconds, minutes } = Duration
const period = minutes.of(5)
setTimeout(doSomething, milliseconds.from(period))
Well, that looks like more code. Yes, it is. It is also more semantically expressive of the programmer's intent, which makes it better for maintenance.
The situation is exacerbated when you expose a programming API that takes a time duration as a number
. We all know that setTimeout
takes milliseconds, but how do you communicate to consumers of your API what the time units are for timeout
in your API call?
You should, of course, document it, and put it in JSDoc comments so that they can get hinting in their IDE.
You could call it timeoutSeconds
to make it clear that it expects seconds.
Or you could make it take a TimeDuration
and allow them to pass in whatever they want, and convert it to the units you need, like this:
import { Duration, TimeDuration } from 'typed-duration'
function executePeriodically(fn: () => void, period: TimeDuration) {
setTimeout(fn, Duration.milliseconds.from(period))
}
Now, consumers of this function can call it like this:
import { Duration } from 'typed-duration'
const { milliseconds, seconds, minutes, hours, days } = Duration
executePeriodically(doSomething, milliseconds.of(2500))
executePeriodically(doSomething, seconds.of(10))
executePeriodically(doSomething, minutes.of(15))
executePeriodically(doSomething, hours.of(3))
executePeriodically(doSomething, days.of(6))
#winning
Backward-compatible API
If you have an existing API you want to add this to, you can use the MaybeTimeDuration
type, like this:
import { Duration, MaybeTimeDuration } from 'typed-duration'
function executePeriodically(fn: () => void, period: MaybeTimeDuration) {
setTimeout(fn, Duration.milliseconds.from(period))
}
executePeriodically(doSomething, Duration.seconds.from(20))
executePeriodically(doSomething, 2500)
Feature Requests, Bug Reports
See the GitHub repo.