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

@vcsuite/check

v2.1.0

Published

check utilities for input type safety

Downloads

1,725

Readme

@vcs/check

A small library to check input variables. The main goal is to sanitize user input and create humanly readable error messages from argument errors. Performance is not a main target. If checking large amounts of data, use where callbacks or create a custom input validation function.

Installation

npm i @vcs/check

Usage

The general idea, is to validate user input:

import { check, Integer, NonEmptyString } from '@vcs/check';

/**
 * checking of input parameters
 */
function foo(bar: number, baz: string[], foobar: object): void {
  check(bar, Number); // bar must be a number
  check(bar, 5); // bar must be 5
  check(bar, Integer); // bar must be an integer value
  check(baz, [String]); // baz must be an array of strings
  check(baz, [NonEmptyString]); // baz must be an array of strings and the values may not be ''
  check(foobar, { bar: Number, baz: [Boolean] }); // foobar must be an object where property bar is a number and property baz an array of booleans
}

You can also check overloaded inputs using oneOf:

import { check, oneOf } from '@vcs/check';

function foo(
  bar: number | string,
  baz: number[] | string[],
  foobar: object | boolean,
): void {
  check(bar, oneOf(Number, String)); // bar must be a number or a string
  check(bar, oneOf(5, '5')); // bar must 5 or '5'
  check(baz, oneOf([Number], [String])); // baz must be an array of numbers or a string
  check(foobar, oneOf({ bar: Number, baz: oneOf(Boolean, String) }, Boolean)); // foobar must be an object where bar is a number and baz is either a boolean or a string or a boolean
}

Instead of using oneOf<T>(undefined, T) to define optional or possible inputs, you can use the maybe or optional helpers:

import { check, maybe, optional } from '@vcs/check';

function foo(bar?: number, baz?: number): void {
  check(bar, maybe(Number)); // bar must be an number or null or undefined
  check(baz, optional(Number)); // baz must be a number or undefined
}

If you check for object patterns using Record<string, Pattern>, you will ensure, the keys on your object have the given types. Additional keys are simply ignored. Sometimes, you would like to ensure an object has certain keys, and only certain keys. You can use the strict helper for this. The strict helper only checks keys on the level of record it is defined, you would have to use it multiple times to ensure strict keys on nested objects.

import { check, optional, strict } from '@vcs/check';

type StrictOne = { one: number };

const strictOneMatcher = strict({ one: number });
function foo(bar: StrictOne): void {
  check(bar, strictOneMatcher); // bar must have key one and only key one of type number
}

function foobar(bar: { foo: StrictOne; bar?: number }): void {
  check(bar, { foo: strictOneMatcher, bar: optional(number) });
}

function baz(bar: { foo: { one: number | string } }): void {
  check(bar, { foo: strict({ one: oneOf(Number, String) }) }); // bar must have key one and only key one of type number or string
}

function deepFoo(bar: { foo: { bar: StrictOne } }): void {
  check(bar, strict({ foo: strict({ bar: strictOneMatcher }) })); // bar must have key foo and only key foo which must have key bar and only key bar which must have key one and only key one of type number
}

You can create custom matchers with where. This can provide better type safety or better performance. For instance, you can use is as a type guard to transform unknown to a custom type using where:

import { is, where } from '@vcs/check';

type Coordinate = [number, number, number];

function offset(coordinate: Coordinate, offset: number): Coordinate {
  return [
    coordinate[0] + offset,
    coordinate[1] + offset,
    coordinate[2] + offset,
  ];
}

function isCoordinate(coordinate: unknown): coordinate is Coordinate {
  if (
    Array.isArray(coordinate) &&
    coordinate.length === 3 &&
    coordinate.every(Number.isFinite)
  ) {
    return true;
  }
  return false;
}

function foo(coordinate: unknown): void {
  if (is(coordinate, where<Coordinate>(isCoordinate))) {
    offset(coordinate, 10);
  }
}

Sometimes you have arbitrary records and you wish to ensure all values have the same type but the keys are user defined (for instance a record of Tags). You can use the recordOf helper to ensure a Record has a certain type:

import { check, recordOf } from '@vcs/check';

function foo(bar: Record<string, string>): void {
  check(bar, recordOf(String)); // bar must be an object with string keys and all values must be strings
}

If you use enumeration in your TS code, checking oneOf doesn't give you the required typeof you're looking for. To use check as a type guard for enumerations, you can use the ofEnum helper as follows. The way TS transpiles enums, makes this only work with string enumerations.

import { check, ofEnum } from '@vcs/check';

enum Baz {
  ONE = 'one',
  TWO = 'two',
  THREE = 'three',
}

function foo(bar: unknown): void {
  check(bar, ofEnum(Baz)); // bar is assignable to Baz enum;
  const baz: Baz = bar; // safe
  console.log(baz);
}

If you use literalTypes in your TS code, you can use the ofLiteralType helper as follows.

import { check, ofLiteralType } from '@vcs/check';

const fooBar = ['one', 'two', 'three'];
type FooBar = (typeof fooBar)[number];

function foo(bar: unknown): void {
  check(bar, ofLiteralType(fooBar));
  const test: FooBar = bar; // safe
  console.log(baz);
}

Furthermore, there are some numeric range & value helpers to ensure numbers are in a certain validity range, such as inRange & gte

import { check, gte, inRange, Integer } from '@vcsuite/check';

function foo(bar: number, baz: number): void {
  check(bar, inRange(0, 2)); // bar must be a number greater equal 0 and less then equal 1;
  check(bar, inRange(0, 2, Integer)); // bar must be an integer number greater equal 0 and less then equal 2
  check(baz, gte(0)); // bar must be a number greater equal 0
  check(baz, gte(0, Integer)); // bar must be an integer number greater equal 0
}