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

simple-type-guard

v3.4.0

Published

This module allows you to quickly and safely validate variables against a defined template, enforced by Typescript. No hassle and easy to scan.

Downloads

58

Readme

Simple Type Guard

Installation

$ npm i -D simple-type-guard

Why Simple Type Guard?

Simple Type Guard takes the guess-work out of validating unknown variables against a type.

No longer will you have to carefully review your code to make sure you're validating every detail of an object to see if it fits.

Simple Type Guard will help you craft the template that perfectly matches your interface and warns you if something is missing or improperly defined.

Even better, you don't have to learn a new pattern or all the facets of a new library. The templates you match against are all standard Javascript.

All you have to do is provide a Generic type!

Examples

Primitives

All primitives will take the typeof value postfixed to Simple to compare against

import simpleTypeGuard, {
  SimpleString,
  SimpleBoolean,
  SimpleNumber,
} from 'simple-type-guard';

simpleTypeGuard<string>('hello world', SimpleString); // -> true

simpleTypeGuard<string>(1234, SimpleString); // -> false

simpleTypeGuard<boolean>(true, SimpleBoolean); // -> true

simpleTypeGuard<number>(0987, SimpleNumber); // -> true

Objects

Objects you can write just like you would an interface!

import simpleTypeGuard, { SimpleNumber } from 'simple-type-guard';

interface Foo {
  bar: number;
}

simpleTypeGuard<Foo>({ bar: 1234 }, { bar: SimpleNumber }); // -> true

simpleTypeGuard<Foo>({ bar: 'invalid string value' }, { bar: SimpleNumber }); // -> false

Arrays

Arrays will attempt to match every iteration of the passed in value to the first index of the template array.

import simpleTypeGuard, { SimpleNumber, SimpleArray } from 'simple-type-guard';

interface Foo {
  list: FooListItem[];
}

interface FooListItem {
  bar: number;
}

simpleTypeGuard<Foo>(
  { list: [{ bar: 1234 }, { bar: 1276 }, { bar: 12973 }] },
  {
    list: SimpleArray<FooListItem>({ bar: SimpleNumber }),
  }
); // -> true

simpleTypeGuard<Foo>(
  { list: [{ bar: 1234 }, { bar: 1276 }, { bar: 'invalid string value' }] },
  {
    list: [{ bar: SimpleNumber }],
  }
); // -> false

Enums

If you have a type consisting of a number of enums (ie type Color = 'red' | 'blue' | 'green'), consider using SimpleExactMatch. Every parameter will be matched against.

import simpleTypeGuard, { SimpleExactMatch } from 'simple-type-guard';

const colors = ['red', 'blue', 'green'];
type Color = typeof colors[number]; // 'red' | 'blue' | 'green'

simpleTypeGuard<Color>('red', new SimpleExactMatch(...colors)); // -> true

Unions

If you have a union consisting of multiple conflicting types, SimpleOr can be used to iterate through each possible type. Every parameter will be matched against.

NOTE: Booleans behave weirdly in Typescript when separating through unions. (boolean turns into true | false). To avoid issues, any time a boolean occurs within the SimpleOr, it must be the last value in the parameters.

For example: string | boolean | number -> new SimpleOr(SimpleString,SimpleNumber,SimpleBoolean)

import simpleTypeGuard, { SimpleOr } from 'simple-type-guard';

interface Car {
  model: string;
}

interface Person {
  company: string;
}

type Foo = Car | Person;

simpleTypeGuard<Foo>(
  { company: 'willowtree' },
  new SimpleOr({ model: SimpleString }, { company: SimpleString })
); // -> true

Functions

If you wanted a lot more control over how a type is validated, 'simple-type-guard' allows you to implement a function for a more specific validation test.

import simpleTypeGuard, { SimpleFunction } from 'simple-type-guard';

interface Foo {
  bar: 'one' | 'two' | 'three';
}

simpleTypeGuard<Foo>(
  { bar: 'one' },
  {
    bar: new SimpleFunction(
      (barVariable: unknown) =>
        ['one', 'two', 'three'].indexOf(barVariable) !== -1
    ),
  }
); // -> true

Optionals

Primitives

Primitive optionals are the same 'Simple' but with an 'Optional' postfix.

import simpleTypeGuard, { SimpleStringOptional } from 'simple-type-guard';

simpleTypeGuard<string | undefined>('hello world', SimpleStringOptional); // -> true

simpleTypeGuard<string | undefined>(undefined, SimpleStringOptional); // -> true

simpleTypeGuard<string | undefined>(1234, SimpleStringOptional); // -> false

This will also allow for null values.

...
simpleTypeGuard<string | null>(null, SimpleStringOptional); // -> true

Objects

Objects require using SimpleObjectOptional to indicate they may be undefined.

import simpleTypeGuard, {
  SimpleObjectOptional,
  SimpleNumber,
} from 'simple-type-guard';

interface Foo {
  bar: number;
}

simpleTypeGuard<Foo | undefined>(
  undefined,
  new SimpleObjectOptional<Foo>({ bar: SimpleNumber })
); // -> true

Arrays

import simpleTypeGuard, {
  SimpleNumber,
  SimpleArrayOptional,
} from 'simple-type-guard';

interface Foo {
  list?: FooListItem[];
}

interface FooListItem {
  bar: number;
}

simpleTypeGuard<Foo>(
  { list: undefined },
  {
    list: new SimpleArrayOptional<FooListItem[]>({ bar: SimpleNumber }),
  }
); // -> true

Options

throwErrorOnFailure (default: false)

When true, will throw an error when an incompatibility is found. This error will provide details on what went wrong.

import simpleTypeGuard, { SimpleString } from 'simple-type-guard';

interface Foo {
  bar: string;
}

simpleTypeGuard<Foo>(
  { bar: 173 },
  { bar: SimpleString },
  { throwErrorOnFailure: true }
); // ->
/**
 * Error: Invalid type detected at
 * "_root_.bar:
 * Expected "string"
 * Found "number"
 *
 * Variable Output: 173
 */