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

generic-type-guard

v5.0.2

Published

Generic type guards for TypeScript

Downloads

48,950

Readme

generic-type-guard

npm

Synopsis

This library is an attempt to manage creating type guards in a sensible way, making them composable and reusable.

Installation

$ npm i generic-type-guard

Usage

The point of this library is to provide a suite of type guard expressions that are themselves both type safe and composable in a type safe way. To that end we define two new types which are just aliases for the built-in type guard type:

export type PartialTypeGuard<T, U extends T> = (value: T) => value is U;
export type TypeGuard<T> = PartialTypeGuard<unknown, T>;

A PartialTypeGuard is a type guard which given a value of type T can prove it is actually the specialised type U. A TypeGuard is a type guard that can prove any value to be of type T; it is a PartialTypeGuard<unknown, T>.

Type safety

What do we mean by type safety when we're talking about something that in a lot of ways is inherantly type unsafe? We simply mean that if you change the definition your interface/variable/whatever you are checking then your type guard should no longer successfully compile. Most of the type safety comes from leveraging the compiler, therefore you must define your typeguards in the following way to make them the most effective:

interface Foo {
	foo: string;
	bar: number;
}

// this fails.
const isBrokenFoo: tg.TypeGuard<Foo> = tg.isRecord('foo', tg.isString);

// this works.
const isFoo: tg.TypeGuard<Foo> = new tg.IsInterface()
	.withProperty('foo', tg.isString)
	.withProperty('bar', tg.isNumber)
	.get();

// This works around the gotchas explained below but has other issues, especially with complex types.
// All guarantees are void if you use this format.
const isFoo = new tg.IsInterface().withProperty('foo', tg.isString).withProperty('bar', tg.isNumber).get();

It is highly recommended to assign an explicit type to the type guards you create to let the compiler ensure that you've caught everything.

Examples

Some examples:

import * as tg from 'generic-type-guard';

export const isComplexInterface = new tg.IsInterface()
	.withProperties({
		str: tg.isString,
		num: tg.isNumber,
		b: tg.isBoolean,
		maybeString: tg.isOptional(tg.isString),
		nullableString: tg.isNullable(tg.isString),
	})
	.get();
export type ComplexInterface = tg.GuardedType<typeof isComplexInterface>;

There are more detailed examples available.

Gotchas

TypeScript structural typing

generic-type-guard works with the TypeScript type system. You are guaranteed that the type guards you write are sufficient to prove that the thing provided to it conforms in one way or another to the type that the type guard checks for. But that doesn't necessarily mean that all valid values of that type will be allowed. Put another way, you are guaranteed to never get a false positive but you may get false negatives. In particular, union types can be troublesome.

An example helps illustrate this:

import * as tg from 'generic-type-guard';

type FooBar = 'foo' | 'bar';

const isFooBar: tg.TypeGuard<FooBar> = tg.isSingletonString('foo');

The above example checks for a single value "foo". This is a FooBar and so the type system does not complain. But if you try to pass "bar" into this type guard then it will return false.

Perhaps more insidiously:

interface Foo {
	foo?: string;
}

const isFoo: tg.TypeGuard<Foo> = tg.isRecord('foo', tg.isString);

Again, checking that foo is a string is sufficient to prove that it is either a string or undefined.

Fix for structural typing issues

If possible, you should reframe the question. Instead of creating a type to guard against, create a guard and export the type:

const isFoo = tg.isRecord('foo', tg.isOptional(tg.isString));
type Foo = tg.GuardedType<typeof isFoo>;