resultt
    TypeScript icon, indicating that this package has built-in type declarations

    2.0.6 • Public • Published

    CircleCI

    ResultT

    ts/js users cannot use try-catch as expression so that we have to struggle with complicated runtimes.

    ResultT is type-safe runtime wrapping library. Strongly inspired by Kotlin Result implementation.

    Install

    From npm registry...

    npm i resultt
    

    type declaration is included.

    class import...

    import { Resultt } from 'resultt';

    Usage

    Try to start from runCatching method. This wraps the result of success or failure.

    // sample logic and response interface
    interface Response {
        data: string
    }
    class Service {
        execute(value: string): Response {
        return {data: value};
        }
    }
    
    // execute some function and wrap by "runCatching"
    const result: Result<Response> = Result.runCatching(() => {
            return new Service().execute('execution');
        })
        .onSuccess((v) => {
            console.log(`response => ${v}`);
            return v
        });
        .onFailure((it: Error) => {
            console.error(it);
            return {
                data: 'DEFAULT'
            };
        });
    
    // You may get the value of execute by "get" functions as declarative.
    const v1 = result.getOrThrow();  // => success ... { data: execution }
    const v2 = result.getOrDefault({
        data: 'OTHER'
    });
    
    // You can process as commandly.
    let v;
    if (result.isSuccess()) {
        v = result.getOrThrow();
    }
    
    // Map the result to another map by fold.
    const folded: number = Result.runCatching(() => {
            return new Service().execute('execution');
        })
        .fold(
            (data: Response) => {
                console.log(data);
                return data.data.length;
            },
            (it: Error) => {
                console.log(it);
                return 0;
            },
        );
    console.log(folded);  // => 9
    
    // Or, shorthand for fold with getOrElse
    const n: number = Result.runCatching(() => {
            return new Service().execute('execution');
        })
        .getOrElse((it: Error) => {
                console.log(it);
                return 0;
            },
        );
    console.log(n);  // => 9

    For more info...

    Full class documentation is here: docs

    Keywords

    Install

    npm i resultt

    DownloadsWeekly Downloads

    6

    Version

    2.0.6

    License

    MIT

    Unpacked Size

    81.8 kB

    Total Files

    19

    Last publish

    Collaborators

    • snozaki