npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ts-code-contracts

v1.0.0

Published

Design by contract with TypeScript.

Downloads

82

Readme

ts-code-contracts

npm Build coverage minified + gzip

Design by contract with TypeScript.

Installation & Usage

npm i ts-code-contracts

Requires TypeScript^3.7

You can now import the following functions from 'ts-code-contracts':

Make sure to checkout the examples in the documentation below or refer to the test cases and typing assistance!

Contracts are really just handy shorthands to throw an error, if the given condition is not met. And yet they greatly help the compiler and the readability of your code.

requires

Use it to validate preconditions, like validating arguments. Throws a PreconditionError if the condition is false.

function requires(
  condition: boolean,
  message: string = 'Unmet precondition'
): asserts condition;
  • condition - the condition that should be true
  • message - an optional message for the error

Example:

function myFun(name: string) {
  requires(name.length > 10, 'Name must be longer than 10 chars');
}

requiresNonNullish

A variation of requires that returns the given value unchanged if it is not null or undefined. Throws a PreconditionError otherwise.

function requiresNonNullish<T>(
  value: T,
  message = 'Value must not be null or undefined'
): NonNullable<T>;
  • value - the value that should not be null or undefined
  • message - an optional message for the error

Example:

function myFun(name: string | null) {
  const nameNonNull = requiresNonNullish(name, 'Name must be defined');
  nameNonNull.toUpperCase(); // no compiler error!
}

checks

Use it to check for an illegal state. Throws a IllegalStateError if the condition is false.

function checks(
  condition: boolean,
  message = 'Callee invariant violation'
): asserts condition;
  • condition - the condition that should be true
  • message - an optional message for the error

Example:

class Socket {
  private isOpen = false;
  send(data: Data) {
    check(this.isOpen, 'Socket must be open');
  }
  open() {
    this.isOpen = true;
  }
}

checksNonNullish

A variation of checks that returns the given value unchanged if it is not null or undefined. Throws a IllegalStateError otherwise.

function checksNonNullish<T>(
  value: T,
  message = 'Value must not be null or undefined'
): NonNullable<T>;
  • value - the value that should not be null or undefined
  • message - an optional message for the error

Example:

class Socket {
  data: Data | null = null;
  send() {
    const validData = checksNonNullish(this.data, 'Data must be available');
    validData.send(); // no compiler error!
  }
}

ensures

Use it to verify that your code behaved correctly. Throws a PostconditionError if the condition is false.

function ensures(
  condition: boolean,
  message = 'Unmet postcondition'
): asserts condition;
  • condition - the condition that should be true
  • message - an optional message for the error

Example:

function myFun() {
  createPerson({ id: 0, name: 'John' });
  const entity = findById(0); // returns null if not present
  return ensures(isDefined(entity), 'Failed to persist entity');
}

ensuresNonNullish

A variation of ensures that returns the given value unchanged if it is not null or undefined. Throws a PostconditionError otherwise.

function ensuresNonNullish<T>(
  value: T,
  message = 'Value must not be null or undefined'
): NonNullable<T>;
  • value - the value that should not be null or undefined
  • message - an optional message for the error

Example:

function myFun(): Person {
  createPerson({ id: 0, name: 'John' });
  const entity = findById(0); // returns null if not present
  return ensuresNonNullish(entity, 'Failed to persist entity');
}

asserts

Clarify that you think that the given condition is impossible to happen. Throws a AssertionError if the condition is false.

asserts(
  condition: boolean,
  message?: string
): asserts condition;
  • condition - the condition that should be true
  • message - an optional message for the error

unreachable

Asserts that a code branch is unreachable. If it is, the compiler will throw a type error. If this function is reached at runtime, an error will be thrown.

function unreachable(
  value: never,
  message = 'Reached an unreachable case'
): never;
  • value - a value
  • message - an optional message for the error

Example:

function myFun(foo: MyEnum): string {
  switch (foo) {
    case MyEnum.A:
      return 'a';
    case MyEnum.B:
      return 'b';
    // no compiler error if MyEnum only has A and B
    default:
      unreachable(foo);
  }
}

error

This function will always throw an error. It helps keeping code easy to read and come in handy when assigning values with a ternary operator or the null-safe operators.

function error(message?: string): never;
function error(
  errorType: new (...args: any[]) => Error,
  message?: string
): never;
  • errorType - an error class, defaults to IllegalStateError
  • message - an optional message for the error

Example:

function myFun(foo: string | null) {
  const bar = foo ?? error(PreconditionError, 'Argument may not be null');
  const result = bar.length > 0 ? 'OK' : error('Something went wrong!');
}

isDefined

A type guard, to check that a value is not null or undefined. Make sure to use strictNullChecks.

function isDefined<T>(value: T): value is NonNullable<T>;
  • value - the value to test

Example:

const x: string | null = 'Hello';
if (isDefined(x)) {
  x.toLowerCase(); // no compiler error!
}

Errors

The following error classes are included:

  • PreconditionError → An error thrown, if a precondition for a function or method is not met.
  • IllegalStateError → An error thrown, if an object is an illegal state.
  • PostconditionError → An error thrown, if a function or method could not fulfil a postcondition.
  • AssertionError → An error thrown, if an assertion has failed.