Skip to content

Latest commit

 

History

History
92 lines (67 loc) · 2.94 KB

README.md

File metadata and controls

92 lines (67 loc) · 2.94 KB

result-ts logo

Rust's Result and Option types, for TypeScript.


results-ts provides Rust-style Result and Option types with chainable methods. Result<T, E> represents a value or an error. Option<T> represents a value that may be absent.

npm version npm canary version documentation Release workflow

Installation

bun add results-ts
# or
npm install results-ts
# or
pnpm add results-ts
# or
deno add results-ts
# or
yarn add results-ts

Usage

Return Ok or Err, then transform or handle the result:

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 message = parseUserId('10')
    .map((id) => id + 3)
    .andThen((id) => Ok({ id, name: 'Alice', role: 'admin' }))
    .match({
        Ok: (user) => `Welcome, ${user.role} ${user.name}!`,
        Err: (error) => `Validation Error: ${error.message}`
    });

console.log(message);

Documentation

See the guides and API reference.

Install the agent skill for guidance on using the library:

bunx skills add madkarmaa/results-ts --skill results-ts

Contributing

See CONTRIBUTING.md for setup and pull request requirements.

Attribution

Contributors

Contributors

License

MIT License.