Skip to content

Instantly share code, notes, and snippets.

@farhad-taran
Last active August 7, 2021 20:53
Show Gist options
  • Save farhad-taran/1df8a12f81fba5b3f9879e3b090fc9cd to your computer and use it in GitHub Desktop.
Save farhad-taran/1df8a12f81fba5b3f9879e3b090fc9cd to your computer and use it in GitHub Desktop.
Result and ErrorResponse pattern in typescript

Following is an implementation of the result monad, this monad can be used in place of throwing errors:

Result Type:

class Result<T>{
    private constructor(success: boolean, content: T, error: IErrorResponse | null) {
        this.success = success;
        this.error = error;
    }
    static success<T>(content: T) {
        return new Result<T>(true, content, null);
    }
    static void() {
        return new Result(true, null, null);
    }
    static failure(error: IErrorResponse)
    {
        if (!error)
        {
            throw new Error('error is required')
        }
        return new Result(false,null, error);
    }
    success: boolean;
    error: IErrorResponse | null;
}

Error Response:

interface IErrorResponse{
    code: string;
    message: string;
}

class ErrorResponse implements IErrorResponse{
    constructor(code: string, message: string) {
        this.code = code;
        this.message = message;
    }
    public code: string;
    public message: string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment