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

inferred

v0.0.10

Published

Typescript library to declare type-safe models by inferring model types from their validators.

Downloads

20

Readme

inferred

This is a typescript library for safe and convenient creation of validation functions and type guards. The key idea is to write your validation code as the source of truth, and infer your model types from the validation code. This ensures that the two are always in sync; it's not possible to change the model type and forget to update the validation code.

Your model types are described by declaring validators using a fluent interface:

const aPhone = anObject({
    phoneNumber: aString,
    phoneType: aStringUnion("Home", "Business", "Mobile", "Unknown")
});

const aPerson = anObject({
    name: aString,
    phones: aPhone.array.orUndefined
});

/* Infer the Person type from its validation code. */
type Person = InferType<typeof aPerson>;

const p: Person = {
    name: "Bob",
    phones: [{ phoneNumber: "123", phoneType: "Mobile" }]
};

aPerson.validate(p); /* Throws if p is not a Person. */

const q = JSON.parse(JSON.stringify(p));

if (aPerson.isValid(q)) {
    /* Validates that q is a Person and narrows its type from any to Person. */
    console.log(`Hello, ${q.name}`);
}

All of the basic types are supported, and validators can be composed to form more complex types. Here is an example that creates a tagged union:

const anOutcome = anObject({
    kind: aStringLiteral("Success"),
    data: aString.array,
    timestamp: aNumber
}).or(
    anObject({
        kind: aStringLiteral("Error"),
        error: aString,
        stackTrace: aString.orUndefined
    })
);

type Outcome = InferType<typeof anOutcome>;

/* Inferred type:
type Outcome = {
    readonly kind: "Success";
    readonly data: ReadonlyArray<string>;
    readonly timestamp: number;
} | {
    readonly kind: "Error";
    readonly error: string;
    readonly stackTrace?: string | undefined;
}
*/

Properties that may be undefined can be declared using .orUndefined, and will become optional properties in the inferred type. If you want a required property, consider using .orNull instead of .orUndefined, and let null signal the absence of a value. Using null instead of undefined also has the advantage of surviving JSON serialization and deserialization.

Validators can be self-referential to support linked data structures like lists and trees. To reference itself, a validator must use a thunk, i.e. a parameterless function, like so:

interface List {
    value: number;
    next: List | null;
}

const aList: Validator<List> = anObject({
    value: aNumber,
    next: () => aList.orNull /* self-reference */
});

const list: List = {
    value: 1,
    next: {
        value: 4,
        next: {
            value: 9,
            next: {
                value: 16,
                next: null
            }
        }
    }
};

aList.validate(list);

Unfortunately, typescript cannot infer the type of a self-referencing initializer, so if you need to use this mechanism, you must declare the model type manually. Also, there is currently no detection of cycles, so if you try to validate e.g. a circularly linked list, the validation code will recurse infinitely. In practice, such situations should be rare; for example, any JSON data will be acyclic by nature.

If you really want to, it's also easy to create your own validators. Use the makeValidator function as in the example below. Custom validators can be combined in the usual way.

class Hex {
    constructor(public readonly digits: string) {}
}

const aHexString = makeValidator((value, options, context) => {
    if (typeof value !== "string" || !value.match(/^[0-9A-Fa-f]+$/)) {
        return context.fail(
            `expected a string of hex digits, not ${context.typeName(value)}`
        );
    }

    return new Hex(value);
});

if (aHexString.isValid("Bad")) {
    console.log("Good!");
}

const aResponse = anObject({
    data: aHexString.array.orNull
});