@reasonable-stack/types
v0.3.0
Published
A reasonably good collection of utility types: Maybe, Result, Decimal and datetime primitives.
Maintainers
Readme
@reasonable-stack/types
A reasonably good collection of utility types for TypeScript.
| type | represents | example / variants |
| :------------- | :------------------------------------------- | :------------------------- |
| Maybe<T> | a value that may or may not be there | Some<T>, None |
| Result<T, E> | the outcome of an operation that may fail | Ok<T>, Error<E> |
| Decimal | an exact decimal number, of any precision | -123.45 |
| Date | a calendar date, no time and no timezone | 2024-02-29 |
| Time | a wall-clock time, no date and no timezone | 13:45:00.000 |
| DateTime | an instant, in UTC | 2024-02-29T13:45:00.000Z |
| Duration | an exact length of time, in days and smaller | P1DT12H |
Maybe and Result are plain TypeScript types, each with a namespace of the
same name holding its constructors, type guards and a match helper.
Decimal, Date, Time, DateTime and Duration are small immutable
classes. No dependencies.
Installation
npm install @reasonable-stack/typesQuick start
import { Maybe, Result } from '@reasonable-stack/types';
const findUser = (id: number): Maybe<{ name: string }> =>
id === 1 ? Maybe.some({ name: 'Ada' }) : Maybe.none();
Maybe.match(findUser(1), {
some: (user) => `hello, ${user.name}`,
none: () => 'who?',
}); // => 'hello, Ada'
const parse = (input: string): Result<number, string> => {
const n = Number(input);
return Number.isNaN(n) ? Result.error(`not a number: ${input}`) : Result.ok(n);
};
Result.match(parse('abc'), {
ok: (n) => n * 2,
error: (message) => message,
}); // => 'not a number: abc'import { Date, DateTime, Duration, Time } from '@reasonable-stack/types';
const due = Date.parse('2024-02-28').add(Duration.days(2));
due.toISOString(); // => '2024-03-01'
const meeting = DateTime.parse('2024-02-29T13:45-03:00');
meeting.add(Duration.minutes(90)).toISOString(); // => '2024-02-29T18:15:00.000Z'
const lunch = Time.parse('12:00');
lunch.diff(Time.parse('13:30')).toISOString(); // => 'PT1H30M'
JSON.stringify({ due, meeting }); // => '{"due":"2024-03-01","meeting":"2024-02-29T16:45:00.000Z"}'Tip: importing
Dateby name shadows the nativeDatein that module. If you need both, rename it on import (import { Date as CalendarDate } from '@reasonable-stack/types') or use a namespace import (import * as t from '@reasonable-stack/types').
Maybe and Result
Common behavior
Both types follow the same rules:
- Construction. Each variant has a lowercase constructor:
Maybe.some(value),Maybe.none(),Result.ok(value),Result.error(value). - Unwrapping. Every variant has an
unwrap()method returning the value it holds. It never throws:Noneunwraps tonull, andErrorunwraps to its error value. - Type guards.
Maybe.isSome/Maybe.isNoneandResult.isOk/Result.isErrornarrow a value to one of its variants, sounwrap()is typed accordingly. - Matching.
match(value, cases)calls the case for the value's variant and returns its result. Cases must be exhaustive, so a forgotten variant is a compile-time error. - Tagged by symbol. Variants are told apart by a
Symbol.for(...)key, so values created by different copies of this package are still recognized.
const user = findUser(1);
if (Maybe.isSome(user)) {
user.unwrap().name; // => 'Ada', typed as string
}
const result = parse('7');
if (Result.isOk(result)) {
result.unwrap() + 1; // => 8, typed as number
} else {
result.unwrap().toUpperCase(); // typed as string
}Note: values are plain objects with a symbol key and a function, so
JSON.stringifyturns them into{}. Unwrap them before serializing.
Maybe
A value that may be absent: either Some<T>, holding a value, or None.
Maybe.some(42); // Some<number>
Maybe.none(); // None| function | returns | description |
| :----------------------------- | :-------- | :-------------------------------------------- |
| some(value) | Some<T> | wraps a value |
| none() | None | the absence of a value |
| isSome(maybe) | boolean | narrows to Some<T> |
| isNone(maybe) | boolean | narrows to None |
| match(maybe, { some, none }) | S \| U | some(value) for Some, none() for None |
Result
The outcome of an operation that may fail: either Ok<T>, holding a value, or
Error<E>, holding an error. The error can be anything, not only an instance
of the native Error.
Result.ok(42); // Ok<number>
Result.ok('done'); // Ok<'done'>
Result.error('not found'); // Error<'not found'>
Result.error(new Error('boom')); // Error<Error>
Result.ok(); // Ok<void>
Result.error(); // Error<void>| function | returns | description |
| :----------------------------- | :--------- | :----------------------------------------------- |
| ok(value?) | Ok<T> | a successful outcome |
| error(value?) | Error<E> | a failed outcome |
| isOk(result) | boolean | narrows to Ok<T> |
| isError(result) | boolean | narrows to Error<E> |
| match(result, { ok, error }) | S \| U | ok(value) for Ok, error(value) for Error |
Result.match(parse('42'), {
ok: (n) => n * 2,
error: (message) => message,
}); // => 84Tip: inside the
Resultnamespace,Erroris the failed variant, not the nativeError. Refer to it asResult.Error<E>to avoid confusion.
Decimal
An exact decimal number, of any precision, inspired by Elixir's
decimal. Use it wherever 0.1 + 0.2 must be 0.3:
money, quantities, NUMERIC database columns.
import { Decimal } from '@reasonable-stack/types';
0.1 + 0.2; // => 0.30000000000000004
Decimal.from(0.1).add(0.2).toString(); // => '0.3'
const price = Decimal.parse('19.90');
price.mult(3).toString(); // => '59.70'
price.div(3).round(2).toString(); // => '6.63'A decimal is a sign, an integer coefficient and an exponent —
sign * coef * 10 ** exp — so Decimal.parse('-1.50') is
{ sign: -1, coef: 150n, exp: -2 }. Only finite values exist: there is no
NaN, no infinity and no negative zero.
Decimal.parse('-1.50'); // from a string, strict
Decimal.parse('1.2e3'); // exponents are fine
Decimal.from(0.1); // from a number's shortest form, so exactly 0.1
Decimal.from(12345678901234567890n); // from a bigint
new Decimal({ sign: -1, coef: 150n, exp: -2 }); // from its fieldsMalformed strings, NaN, infinities and exponents beyond -6176..6144 throw
a RangeError.
Arithmetic
add, sub, mult and rem are exact. Trailing zeros are kept,
since they carry meaning (1.50 is a price, 1.5 may not be):
Decimal.parse('1.10').add(2).toString(); // => '3.10'
Decimal.parse('1.5').mult('2.0').toString(); // => '3.00'div and sqrt are exact when the result fits in 34 significant digits, and
otherwise round half up to 34 digits, the default precision of Elixir's
decimal. Round the result to the places you need:
Decimal.parse('1').div(4).toString(); // => '0.25'
Decimal.parse('1').div(3).toString(); // => '0.3333333333333333333333333333333333'
Decimal.parse('1').div(3).round(2).toString(); // => '0.33'Dividing by zero, and the square root of a negative, throw a RangeError.
Every operation that takes another operand accepts a Decimal, a number, a
bigint or a string.
| method | returns | description |
| :----------------------------- | :------------- | :------------------------------------------------------------- |
| add(other) | Decimal | the sum |
| sub(other) | Decimal | the difference, this − other |
| mult(other) | Decimal | the product |
| div(other) | Decimal | the quotient, up to 34 significant digits |
| rem(other) | Decimal | the remainder of the integer division, with the sign of this |
| negate() | Decimal | the opposite |
| abs() | Decimal | the absolute value |
| sqrt() | Decimal | the square root, up to 34 significant digits |
| round(places, mode) | Decimal | rounds to exactly places decimal places |
| normalize() | Decimal | drops trailing zeros, 1.50 → 1.5 |
| scale() | number | the number of decimal places, trailing zeros included |
| compare(other) | -1 \| 0 \| 1 | compares values, 1.0 and 1.00 are equal |
| eq, gt, lt, gte, lte | boolean | compares values |
| isInteger() | boolean | whether there are no significant decimal places |
| isPositive() | boolean | whether greater than zero |
| isNegative() | boolean | whether less than zero |
| toBigInt() | bigint | the value as a bigint, throws if it has significant decimals |
| toNumber() | number | the nearest number, which may lose precision |
| toString(format) | string | see below |
Like the date and time types, Decimal has static is, compare, sort,
min and max, so values.toSorted(Decimal.compare) works.
Rounding
round(places = 0, mode = 'half_up') rounds to exactly places decimal
places, adding trailing zeros if needed. Negative places round to tens,
hundreds, and so on.
Decimal.parse('1.235').round(2).toString(); // => '1.24'
Decimal.parse('1.5').round(3).toString(); // => '1.500'
Decimal.parse('155').round(-1).toString(); // => '160'The modes are Elixir's:
| mode | 2.5 | -2.5 | 1.6 | -1.1 |
| :------------ | ----: | -----: | ----: | -----: |
| 'up' | 3 | -3 | 2 | -2 |
| 'down' | 2 | -2 | 1 | -1 |
| 'ceiling' | 3 | -2 | 2 | -1 |
| 'floor' | 2 | -3 | 1 | -2 |
| 'half_up' | 3 | -3 | 2 | -1 |
| 'half_down' | 2 | -2 | 2 | -1 |
| 'half_even' | 2 | -2 | 2 | -1 |
Formatting
toString(format = 'normal') takes one of four formats. toJSON() and
template literals use 'normal', so a decimal serializes as a string and
keeps its precision.
| format | 1.23e3 | 0.0000001 | 1.00 |
| :------------- | :---------- | :------------ | :--------- |
| 'normal' | '1230' | '0.0000001' | '1.00' |
| 'scientific' | '1.23E+3' | '1E-7' | '1.00' |
| 'raw' | '123E1' | '1E-7' | '100E-2' |
| 'xsd' | '1230.0' | '0.0000001' | '1.0' |
JSON.stringify({ price: Decimal.parse('1.50') }); // => '{"price":"1.50"}'Dates and times
JavaScript's native Date is a single type doing the job of several: it is an
instant, a calendar date and a wall-clock time all at once, it silently
accepts invalid input, it counts months from zero and it is mutable. Date,
Time, DateTime and Duration give each concept its own small, immutable
type.
They are meant to be simpler than Temporal: no calendars other than ISO 8601, no IANA timezones, no daylight saving time, no months or years in durations.
Common behavior
Every type follows the same rules:
- Construction.
newtakes the fields; the staticparsereads an ISO string (or, forDateTime, milliseconds since the Unix epoch). - Immutable. Fields are read-only and every operation returns a new instance.
- Strict. Malformed strings and out-of-range fields throw a
RangeErrorinstead of rolling over —2023-02-29,24:00and13:60are all errors. - Months start at 1. January is
1, December is12. - Years range from 0 to 9999, so ISO strings always have a 4-digit year.
Years 0 to 99 are taken literally (
0050is year 50, not 1950). - Serializes as ISO 8601.
toISOString(),toString()andtoJSON()return the same string, so instances work in template literals andJSON.stringify. - Comparison.
a.compare(b)and the staticcompare(a, b)return-1,0or1, so the static one works as anArray.prototype.sortcomparator. diffgoes fromthistoother.a.diff(b)isb − a, soa.add(a.diff(b))is alwaysb.- Collections. Each type has static
sort,minandmax.sortreturns a new array (the input is left untouched);minandmaxthrow aRangeErroron an empty array. - Type guards. Each type has a static
is(value), which narrows an unknown value to that type.
const dates = [Date.parse('2024-03-01'), Date.parse('2023-12-31')];
Date.sort(dates).map(String); // => ['2023-12-31', '2024-03-01']
Date.min(dates).toString(); // => '2023-12-31'
dates.toSorted(Date.compare); // same as `Date.sort(dates)`
Date.is(dates[0]); // => true
Time.is(dates[0]); // => falseThe static compare and sort only take values of their own type, so mixing,
say, a Date and a Time is a compile-time error.
The instance compare is handy for sorting records by one of their fields:
const events = [
{ name: 'launch', at: Date.parse('2024-03-01') },
{ name: 'kickoff', at: Date.parse('2023-12-31') },
];
events.toSorted((a, b) => a.at.compare(b.at)).map((e) => e.name);
// => ['kickoff', 'launch']
events.toSorted((a, b) => b.at.compare(a.at)).map((e) => e.name);
// => ['launch', 'kickoff'] (descending)Date
A calendar date: a year, a month and a day. No time, no timezone.
Date.parse('2024-02-29'); // from an ISO date (YYYY-MM-DD)
new Date({ year: 2024, month: 2, day: 29 }); // from its fields
Date.todayUTC(); // the current date in UTC| field | range |
| :------ | :-------- |
| year | 0..9999 |
| month | 1..12 |
| day | 1..31 |
| method | returns | description |
| :------------------------------- | :------------- | :------------------------------------------- |
| add(duration) | Date | moves forward by a whole number of days |
| sub(duration) | Date | moves backward by a whole number of days |
| diff(other) | Duration | the number of days from this date to other |
| compare(other) | -1 \| 0 \| 1 | compares dates |
| beginningOf('year' \| 'month') | Date | the first day of the year or month |
| endOf('year' \| 'month') | Date | the last day of the year or month |
| toISOString() | string | e.g. '2024-02-29' |
Dates only move in whole days. Adding a duration with leftover hours, minutes,
seconds or milliseconds throws a RangeError:
const date = Date.parse('2024-01-01');
date.add(Duration.hours(48)).toISOString(); // => '2024-01-03'
date.add(Duration.hours(5)); // throws RangeError
Date.parse('2024-02-14').endOf('month').toISOString(); // => '2024-02-29'Time
A wall-clock time, with millisecond precision. No date, no timezone.
Time.parse('13:45'); // HH:MM
Time.parse('13:45:30'); // HH:MM:SS
Time.parse('13:45:30.5'); // HH:MM:SS.s, up to 3 fraction digits
new Time({ hour: 13, minute: 45 }); // second and millisecond default to 0| field | range |
| :------------ | :------- |
| hour | 0..23 |
| minute | 0..59 |
| second | 0..59 |
| millisecond | 0..999 |
| method | returns | description |
| :--------------- | :------------- | :------------------------------------------- |
| add(duration) | Time | moves forward, wrapping around midnight |
| sub(duration) | Time | moves backward, wrapping around midnight |
| diff(other) | Duration | the time from this time to other |
| compare(other) | -1 \| 0 \| 1 | compares times |
| toISOString() | string | always HH:MM:SS.sss, e.g. '13:45:00.000' |
Times wrap around midnight, so adding whole days leaves a time unchanged:
Time.parse('23:00').add(Duration.hours(2)).toISOString(); // => '01:00:00.000'
Time.parse('10:00').add(Duration.days(3)).toISOString(); // => '10:00:00.000'DateTime
An instant in time, in UTC. The date and time fields are the wall-clock reading in UTC.
DateTime.parse('2024-02-29T13:45:30.5-03:00'); // from an ISO date-time, converted to UTC
DateTime.parse(1709225130500); // from milliseconds since the Unix epoch
new DateTime({ // from its fields, in UTC
year: 2024, month: 2, day: 29,
hour: 13, minute: 45, // time fields default to 0
});
DateTime.nowUTC(); // the current instantISO strings must include an offset, either Z or ±HH:MM. A date-time without
one is ambiguous, so DateTime.parse('2024-02-29T13:45') throws a
RangeError. The offset is only used to find the instant, and is not kept:
DateTime.parse('2024-02-29T13:45-03:00').toISOString(); // => '2024-02-29T16:45:00.000Z'| field | range |
| :------------ | :---------------------------------------- |
| year | 0..9999 |
| month | 1..12 |
| day | 1..31 |
| hour | 0..23 |
| minute | 0..59 |
| second | 0..59 |
| millisecond | 0..999 |
| epoch | milliseconds since 1970-01-01T00:00:00Z |
| method | returns | description |
| :---------------------------------------- | :------------- | :------------------------------------------------ |
| add(duration) | DateTime | moves forward |
| sub(duration) | DateTime | moves backward |
| diff(other) | Duration | the exact time from this instant to other |
| compare(other) | -1 \| 0 \| 1 | compares instants |
| beginningOf('year' \| 'month' \| 'day') | DateTime | the first millisecond of the unit |
| endOf('year' \| 'month' \| 'day') | DateTime | the last millisecond of the unit (23:59:59.999) |
| date() | Date | the date in UTC |
| time() | Time | the time in UTC |
| toNativeDate() | native Date | the same instant as a native Date |
| toISOString() | string | always in UTC, e.g. '2024-02-29T13:45:00.000Z' |
Two ISO strings for the same instant parse to equal date-times, whatever their offsets:
const a = DateTime.parse('2024-01-01T12:00+02:00');
const b = DateTime.parse('2024-01-01T10:00Z');
DateTime.compare(a, b); // => 0
a.diff(b).toISOString(); // => 'PT0S'Because date-times are always in UTC, a day is always exactly 24 hours — there is no daylight saving time to account for. The date and time are read in UTC, which may not be the date and time of the parsed string:
const night = DateTime.parse('2024-02-29T23:30-03:00');
night.date().toISOString(); // => '2024-03-01'
night.time().toISOString(); // => '02:30:00.000'
night.toNativeDate().toISOString(); // => '2024-03-01T02:30:00.000Z'Duration
An exact length of time, positive or negative. Durations have no months or years, since those have no fixed length, so any two durations can be compared.
new Duration({ days: 1, hours: 12 }); // any combination of fields, all optional
Duration.days(1);
Duration.hours(1.5); // fractions are fine: 1 hour and 30 minutes
Duration.minutes(5);
Duration.seconds(30);
Duration.milliseconds(250);Fields are normalized, so every duration has a single representation:
const duration = new Duration({ hours: 36 });
duration.days; // => 1
duration.hours; // => 12| field | range |
| :------------- | :-------- |
| days | any |
| hours | ±0..23 |
| minutes | ±0..59 |
| seconds | ±0..59 |
| milliseconds | ±0..999 |
A negative duration has every field negative: -36 hours is { days: -1,
hours: -12 }. The total is rounded to whole milliseconds, and non-finite
values (NaN, Infinity) throw a RangeError.
| method | returns | description |
| :--------------- | :------------- | :------------------------------------- |
| add(duration) | Duration | the sum |
| sub(duration) | Duration | the difference, this − duration |
| diff(other) | Duration | the difference, other − this |
| compare(other) | -1 \| 0 \| 1 | compares total lengths |
| toISOString() | string | an ISO 8601 duration, e.g. 'P1DT12H' |
Duration.compare(Duration.hours(36), Duration.days(2)); // => -1
new Duration({}).toISOString(); // => 'PT0S'
Duration.milliseconds(-1250).toISOString(); // => '-PT1.25S'Helpers
The most common static methods are also exported as plain functions, for shorter call sites:
| helper | same as |
| :---------------- | :---------------------------------------------------------------------------- |
| nowUTC() | DateTime.nowUTC() |
| todayUTC() | Date.todayUTC() |
| days(n) | Duration.days(n) |
| hours(n) | Duration.hours(n) |
| minutes(n) | Duration.minutes(n) |
| seconds(n) | Duration.seconds(n) |
| milliseconds(n) | Duration.milliseconds(n) |
| sort(items) | Date.sort(items), Decimal.sort(items), … for whichever type items holds |
| compare(a, b) | a.compare(b) |
import { Date, compare, days, hours, minutes, sort } from '@reasonable-stack/types';
Date.parse('2024-02-28').add(days(2)).toISOString(); // => '2024-03-01'
sort([hours(3), minutes(90)]).map(String); // => ['PT1H30M', 'PT3H']
compare(days(2), hours(36)); // => 1sort and compare work with Date, Time, DateTime, Duration and
Decimal, but in TypeScript all values must be of the same type — mixing,
say, a Date and a Time is a compile-time error, since they can't be
meaningfully compared. As compare returns the -1, 0 or 1 that
Array.prototype.sort expects, it works as a comparator:
values.toSorted(compare).
