Giter Club home page Giter Club logo

ts-pedantic's Introduction

TS Pedantic


Rust like error handling for Typescript.

npm version License


Warning This library is still in its pre-release phase, so the API could change before it hits 1.0. Please feel free to contribute if you find any issues!

Rationale

Options and Results encourage more pedantic error handling. Most importantly, your code indicates whether a function can throw, and in that case exactly what those errors are, at the type level. These patterns encourage you to handle errors meticulously and to write more declarative code with easy APIs telling readers what is to be done in most common error cases. Options and Results prevent the need for try...catch blocks everywhere.

Using Option

We use an Option type when we only care about the value. If we get back a None, we know there is no value and aren't concerned with why the value is empty.

type User = {
  id: string;
  name: string;
};

const getUserOption = (id: string): Option<User> => {
  if (id === '000') {
    return none();
  }

  return some({
    id: '123',
    name: 'John Wick'
  });
};

const userOption = getUserOption('123');
if (userOption.isSome) {
  const user = userOption.value;
  // ^? type user = User
}

Using Result

Result types can be seen as an extension of Option where we're also concerned with the possible causes of an error.

type User = {
  id: string;
  name: string;
};

interface DbReadError extends Error {
  id: string;
}

const getUserResult = (id: string): Result<User, DbReadError> => {
  if (id === '000') {
    return error({
      name: 'DbReadError',
      message: 'This id cannot be used',
      id: 'some-id'
    });
  }

  return ok({
    id: '123',
    name: 'John Wick'
  });
};

// You can imperatively handle the result like so:
const userResult = getUserResult('john');
if (userResult.isOk) {
  const user = userResult.value;
  // ^? type user = User
} else {
  const error = userResult.error;
  // ^? type error = DbReadError
}

To Option or to Result?

Result basically has all the superpowers of Option but with added functionality. When to use either is a question of what tool to use for what job. Use the primitive that best suits your current use-case.

Using Match

You can use match on an Option or Result type to declaratively handle the different cases like so:

match(userOption, {
  onSome: (user) => {
    console.log(user);
  },
  onNone: () => {
    console.error('No user found');
  }
});

match(userResult, {
  onOk: (user) => {
    console.log(user);
  },
  onError: (error) => {
    console.error(`User not found. Cause: ${error}`);
  }
});

ts-pedantic's People

Contributors

renni771 avatar github-actions[bot] avatar

Stargazers

Rafael Santos Sá avatar Laila Los avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.