GithubHelp home page GithubHelp logo

mattcosta7 / outvariant Goto Github PK

View Code? Open in Web Editor NEW

This project forked from open-draft/outvariant

0.0 1.0 0.0 95 KB

Type-safe implementation of invariant with positionals.

Home Page:

License: MIT License

JavaScript 0.87% TypeScript 99.13%

outvariant's Introduction


Type-safe implementation of invariant with positionals.



This implementation asserts the given predicate expression so it's treated as non-nullable after the invariant call:

// Regular invariant:
invariant(user, 'Failed to fetch')
user?.firstName // "user" is possibly undefined

// Outvariant:
invariant(user, 'Failed to fetch')
user.firstName // OK, "invariant" ensured the "user" exists

Positionals support

This implementation uses rest parameters to support dynamic number of positionals:

invariant(predicate, 'Expected %s but got %s', 'one', false)

What is this for?

Invariant is a shorthand function that asserts a given predicate and throws an error if that predicate is false.

Compare these two pieces of code identical in behavior:

if (!token) {
  throw new Error(`Expected a token to be set but got ${typeof token}`)
import { invariant } from 'outvariant'

invariant(token, 'Expected a token to be set but got %s', typeof token)

Using invariant reduces the visual nesting of the code and leads to cleaner error messages thanks to formatted positionals (i.e. the %s (string) positional above).



npm install outvariant
# or
yarn add outvariant

You may want to install this library as a dev dependency (-D) based on your usage.

Write an assertion

import { invariant } from 'outvariant'

invariant(user, 'Failed to load: expected user, but got %o', user)


The following positional tokens are supported:

Token Expected value type
%s String
%d/%i Number
%j JSON (non-stringified)
%o Arbitrary object or object-like (i.e. a class instance)

Whenever present in the error message, a positional token will look up the value to insert in its place from the arguments given to invariant.

  'Expected the "%s" property but got %j',
  // Note that positionals are sensitive to order:
  // - "firstName" replaces "%s" because it's first.
  // - {"id":1} replaces "%j" because it's second.
    id: 1,

Polymorphic errors

It is possible to throw a custom Error instance using

import { invariant } from 'outvariant'

class NetworkError extends Error {
  constructor(message) {
}, res.fulfilled, 'Failed to handle response')

Note that providing a custom error constructor as the argument to requires the custom constructor's signature to be compatible with the Error class constructor.

If your error constructor has a different signature, you can pass a function as the first argument to that creates a new custom error instance.

import { invariant } from 'outvariant'

class NetworkError extends Error {
  constructor(statusCode, message) {
    this.statusCode = statusCode
  (message) => new NetworkError(500, message),
  'Failed to handle response'

Abstract the error into helper functions for flexibility:

function toNetworkError(statusCode) {
  return (message) => new NetworkError(statusCode, message)
}, res?.user?.id, 'User Not Found'), res.fulfilled, 'Internal Server Error')


Please open an issue or submit a pull request if you wish to contribute. Thank you.

outvariant's People


kettanaito 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.