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-auto-guard-err

v1.0.0-alpha.13

Published

Generate type guard functions from TypeScript interfaces

Downloads

1

Readme

ts-auto-guard

Greenkeeper badge

Generate type guard functions from TypeScript interfaces

A tool for automatically generating TypeScript type guards for interfaces in your code base.

This tool aims to allow developers to verify data from untyped sources to ensure it conforms to TypeScript types. For example when initializing a data store or receiving structured data in an AJAX response.

Install

Yarn

$ yarn add -D ts-auto-guard

npm

$ npm install --save-dev ts-auto-guard

Usage

Specify which types to process (see below) and run the CLI tool in the same folder as your project's tsconfig.json (optionally passing in paths to the files you'd like it to parse).

$ ts-auto-guard ./my-project/Person.ts

See generated files alongside your annotated files:

// my-project/Person.guard.ts

import { Person } from './Person'

export function isPerson(obj: any): obj is Person {
  return (
    typeof obj === 'object' &&
    typeof obj.name === 'string' &&
    (typeof obj.age === 'undefined' || typeof obj.age === 'number') &&
    Array.isArray(obj.children) &&
    obj.children.every(e => isPerson(e))
  )
}

Now use in your project:

// index.ts

import { Person } from './Person'
import { isPerson } from './Person.guard'

// Loading up an (untyped) JSON file
const person = require('./person.json')

if (isPerson(person)) {
  // Can trust the type system here because the object has been verified.
  console.log(`${person.name} has ${person.children.length} child(ren)`)
} else {
  console.error('Invalid person.json')
}

Specifying which types to process

Specify with annotation

Annotate interfaces in your project or pass. ts-auto-guard will generate guards only for interfaces with a @see {name} ts-auto-guard:type-guard JSDoc tag.

// my-project/Person.ts

/** @see {isPerson} ts-auto-guard:type-guard */
export interface Person {
  // !do not forget to export - only exported types are processed
  name: string
  age?: number
  children: Person[]
}

Process all types

Use --export-all parameter to process all exported types:

$ ts-auto-guard --export-all

Debug mode

Use debug mode to help work out why your type guards are failing in development. This will change the output type guards to log the path, expected type and value of failing guards.

$ ts-auto-guard --debug
isPerson({ name: 20, age: 20 })
// stderr: "person.name type mismatch, expected: string, found: 20"

Short circuiting

ts-auto-guard also supports a shortcircuit flag that will cause all guards to always return true.

$ ts-auto-guard --shortcircuit="process.env.NODE_ENV === 'production'"

This will result in the following:

// my-project/Person.guard.ts

import { Person } from './Person'

export function isPerson(obj: any): obj is Person {
  if (process.env.NODE_ENV === 'production') {
    return true
  }
  return (
    typeof obj === 'object' &&
    // ...normal conditions
  )
}

Using the shortcircuit option in combination with uglify-js's dead_code and global_defs options will let you omit the long and complicated checks from your production code.

Return errors

Use --return-errors flag to create an extra function that will not acts as typesafe guards, but output an array of appropriate errors (the same errors as given in the debug mode). Intended use is for example integrity testing non typesafe database outputs, that can then be printed to the screen.

$ ts-auto-guard --return-errors
// Generic usage
isObjErrorOut(obj): errors: Error[]

const returnVar = isPersonErrorOut({ name: "John", age: 20 })
// returnVar.length: 0

const returnVar = isPersonErrorOut({ name: 20, age: 20 })
// returnVar[0].message: "person.name type mismatch, expected: string, found: 20"