Socket
Socket
Sign inDemoInstall

outvariant

Package Overview
Dependencies
0
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    outvariant

Type-safe implementation of invariant with positionals.


Version published
Weekly downloads
2.8M
increased by1.12%
Maintainers
1
Install size
22.5 kB
Created
Weekly downloads
 

Package description

What is outvariant?

The outvariant package is a utility library for creating invariant conditions in JavaScript and TypeScript applications. It allows developers to enforce certain conditions or assumptions in their code, throwing errors when those conditions are not met. This can be particularly useful for validating arguments, ensuring application states, or enforcing coding contracts during development.

What are outvariant's main functionalities?

Invariant enforcement

This feature allows developers to enforce conditions within their code. If the condition fails, an error is thrown with a custom message. In the example, an error is thrown if an attempt is made to divide by zero.

import { invariant } from 'outvariant';

function divide(a, b) {
  invariant(b !== 0, 'Attempted to divide by zero.');
  return a / b;
}

Warn

This feature enables developers to issue warnings instead of errors. It's useful for deprecation notices or highlighting undesirable but non-fatal behavior. In the example, a warning is issued for using a deprecated function.

import { warn } from 'outvariant';

function deprecatedFunction() {
  warn('deprecatedFunction is deprecated and will be removed in the next major release.');
}

Other packages similar to outvariant

Readme

Source

outvariant

Type-safe implementation of invariant with positionals.

Motivation

Type-safely

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

Usage

Install

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)

Positionals

The following positional tokens are supported:

TokenExpected value type
%sString
%d/%iNumber
%jJSON (non-stringified)
%oArbitrary 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.

invariant(
  false,
  '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.
  'firstName',
  {
    id: 1,
  }
)

Polymorphic errors

It is possible to throw a custom Error instance using invariant.as:

import { invariant } from 'outvariant'

class NetworkError extends Error {
  constructor(message) {
    super(message)
  }
}

invariant.as(NetworkError, res.fulfilled, 'Failed to handle response')

Note that providing a custom error constructor as the argument to invariant.as 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 invariant.as that creates a new custom error instance.

import { invariant } from 'outvariant'

class NetworkError extends Error {
  constructor(statusCode, message) {
    super(message)
    this.statusCode = statusCode
  }
}

invariant.as(
  (message) => new NetworkError(500, message),
  res.fulfilled,
  'Failed to handle response'
)

Abstract the error into helper functions for flexibility:

function toNetworkError(statusCode) {
  return (message) => new NetworkError(statusCode, message)
}

invariant.as(toNetworkError(404), res?.user?.id, 'User Not Found')
invariant.as(toNetworkError(500), res.fulfilled, 'Internal Server Error')

Contributing

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

Keywords

FAQs

Last updated on 14 Dec 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc