Getting started
Install results-ts, then use Result for errors or Option for optional values.
Installation
bun add results-ts
# or
npm install results-ts
# or
pnpm add results-ts
# or
deno add results-ts
# or
yarn add results-tsBrowser without a bundler
This library is an ES module. To use it directly in a browser, import it from a CDN inside a <script type="module">:
<script type="module">
import { Ok } from 'https://unpkg.com/results-ts/dist/index.js';
console.log(
Ok(1)
.map((x) => x + 1)
.unwrap()
); // 2
</script>Core concepts
Use Result when a failed operation needs an error value. Use Option when a value may be absent and you do not need an error value.
Result
Result<T, E> is either Ok(value) with a value of type T, or Err(error) with an error of type E. Return a Result when callers can recover from a failure.
import { Ok, Err } from 'results-ts';
const parseUserId = (id: string) => {
const parsed = parseInt(id, 10);
if (isNaN(parsed))
return Err({
code: 'INVALID_INPUT',
message: 'ID must be a valid number'
} as const);
if (parsed <= 0)
return Err({
code: 'INVALID_ID',
message: 'ID must be positive'
} as const);
return Ok(parsed);
};
const fetchUser = (id: number) => {
if (id === 13)
return Err({ code: 'NOT_FOUND', message: 'User not found' } as const);
return Ok({ id, name: 'Alice', role: 'admin' });
};
const message = parseUserId('10')
.map((id) => id + 3)
.andThen(fetchUser)
.match({
Ok: (user) => `Welcome, ${user.role} ${user.name}!`,
Err: (error) => {
if (error.code === 'NOT_FOUND')
return `Database Error: ${error.message}`;
return `Validation Error: ${error.message}`;
}
});NOTE
Result.unwrap() and Result.expect() throw on Err. Result.unwrapErr() and Result.expectErr() throw on Ok. Use Result.unwrapOr(), Result.unwrapOrElse(), or Result.match() for recoverable failures. See Error handling.
Option
Option<T> is either Some(value) with a value of type T, or None() with no value. Use its methods to handle a value that may be absent.
import { Some, None } from 'results-ts';
const parseNickname = (nickname?: string) => {
if (!nickname) return None();
const trimmed = nickname.trim();
return trimmed.length > 0 ? Some(trimmed) : None();
};
const displayName = parseNickname(' Ada ')
.map((name) => name.toUpperCase())
.match({
Some: (name) => name,
None: () => 'ANONYMOUS'
});Call None() to create an absent value. Use None<number>() to specify its type. Convert an Option to a Result with Option.okOr(err) or Option.okOrElse(() => err).
Next steps
- Error handling explains panics, invalid arguments, and
catchUnwind. - Async support covers
AsyncResultandAsyncOption. - API reference documents each type and method.