Skip to content

Latest commit

 

History

History
96 lines (72 loc) · 3.08 KB

File metadata and controls

96 lines (72 loc) · 3.08 KB

result-ts logo

Rust's Result and Option types, for TypeScript.


This library mimics the Rust Result and Option enums and includes some of their chainable methods adapted for TypeScript, with full type safety. For full documentation on the usage of the available methods, please refer to the official Rust docs (or read the JSDocs directly in your editor).

npm version npm canary version documentation Release workflow

Installation

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

Usage

A quick taste of the Result type:

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

Full documentation and complete API reference: results-ts.madkarma.top.

Contributing

Interested in contributing? See CONTRIBUTING.md for setup instructions, development guidelines, and pull request expectations.

Attribution

Contributors

Thanks to all the contributors who helped make this project better!

Contributors

License

This project is licensed under the MIT License.