@hexdspace/core
v0.1.0
Published
Result type and other primitives shared across projects
Readme
@hexdspace/core
Primitives shared across projects. No runtime dependencies.
Result
import { type AsyncResult, type Result, mapOk, nok, ok, unwrapOr } from '@hexdspace/core';
function parsePort(raw: string): Result<string, number> {
const port = Number(raw);
return Number.isInteger(port) ? ok(port) : nok(`Bad port: ${raw}`);
}
const result = parsePort('8080');
if (result.ok) {
result.value;
} else {
result.error;
}
unwrapOr(mapOk(result, (port) => port + 1), 3000);The error type comes first: Result<E, T> and AsyncResult<E, T>.
| Function | Purpose |
| --- | --- |
| ok(value), nok(error) | construct a result |
| isOk(result), isNok(result) | type guards |
| mapOk(result, transform) | transform the value |
| mapError(result, transform) | transform the error |
| unwrap(result) | return the value or throw the error |
| unwrapOr(result, fallback) | return the value or the fallback |
Testing
@hexdspace/core/testing has vitest assertions that narrow the type:
import { expectResultError, expectResultOk } from '@hexdspace/core/testing';
expectResultOk(result);
result.value;