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

gen-typed-validators

v1.1.5

Published

convert type annotations to typed-validators

Downloads

98

Readme

gen-typed-validators

CircleCI Coverage Status semantic-release Commitizen friendly npm version

Automatically generate runtime validators from your Flow or TypeScript type definitions! (using typed-validators)

Table of Contents

How it works

Say you want to generate validators for a User type. Just add a const UserType: t.TypeAlias<User> = null declaration after it and run this codemod:

// User.ts

export type Address = {
  line1: string
  line2?: string
  city: string
  zipCode: string
}

export type User = {
  email: string
  firstName?: string
  lastName?: string
  address?: Address
}

export const UserType: t.TypeAlias<User> = null
$ gen-typed-validators User.ts

/Users/andy/github/typed-validators-codemods/User.ts
======================================

+ modified - original

@@ -1,15 +1,44 @@
+import * as t from 'typed-validators'
 export type Address = {
   line1: string
   line2?: string
   city: string
   zipCode: string
 }

+export const AddressType: t.TypeAlias<Address> = t.alias(
+  'Address',
+  t.object({
+    required: {
+      line1: t.string(),
+      city: t.string(),
+      zipCode: t.string(),
+    },
+
+    optional: {
+      line2: t.string(),
+    },
+  })
+)
+
 export type User = {
   email: string
   firstName?: string
   lastName?: string
   address?: Address
 }

-export const UserType: t.TypeAlias<User> = null
+export const UserType: t.TypeAlias<User> = t.alias(
+  'User',
+  t.object({
+    required: {
+      email: t.string(),
+    },
+
+    optional: {
+      firstName: t.string(),
+      lastName: t.string(),
+      address: t.ref(() => AddressType),
+    },
+  })
+)

? write: (y/N)

Type Walking

Notice that the above example also creates an AddressType validator for the Address type, since Address is used in the User type. gen-typed-validators will walk all the dependent types, even if they're imported. For example:

// Address.ts

export type Address = {
  line1: string
  line2?: string
  city: string
  zipCode: string
}

// User.ts

import { Address } from './Address'

export type User = {
  email: string
  firstName?: string
  lastName?: string
  address?: Address
}

export const UserType: t.TypeAlias<User> = null
$ gen-typed-validators User.ts

/Users/andy/github/typed-validators-codemods/Address.ts
======================================

+ modified - original

@@ -1,6 +1,22 @@
+import * as t from 'typed-validators'
 export type Address = {
   line1: string
   line2?: string
   city: string
   zipCode: string
 }
+
+export const AddressType: t.TypeAlias<Address> = t.alias(
+  'Address',
+  t.object({
+    required: {
+      line1: t.string(),
+      city: t.string(),
+      zipCode: t.string(),
+    },
+
+    optional: {
+      line2: t.string(),
+    },
+  })
+)



/Users/andy/github/typed-validators-codemods/User.ts
======================================

+ modified - original

@@ -1,10 +1,25 @@
-import { Address } from './Address'
+import { Address, AddressType } from './Address'

+import * as t from 'typed-validators'
+
 export type User = {
   email: string
   firstName?: string
   lastName?: string
   address?: Address
 }

-export const UserType: t.TypeAlias<User> = null
+export const UserType: t.TypeAlias<User> = t.alias(
+  'User',
+  t.object({
+    required: {
+      email: t.string(),
+    },
+
+    optional: {
+      firstName: t.string(),
+      lastName: t.string(),
+      address: t.ref(() => AddressType),
+    },
+  })
+)

? write: (y/N)

Limitations

  • This codemod currently doesn't preserve formatting, though if it finds prettier installed in your project, it will format the generated code using prettier.

  • Definitely not all types are supported. The goal will always be to support a subset of types that can be reliably validated at runtime.

    Supported types:

    • All primitive values
    • any
    • unknown/mixed
    • Arrays
    • Tuples
    • Unions (|)
    • Intersections (&)
    • Objects or interfaces without indexers or methods
      • Flow exception: only a single indexer, to indicate a record type ({ [string]: number })
      • TS execption: indexers to allow additional properties
        • { foo: number, [string]: any }
        • { foo: number, [string]: unknown }
        • { foo: number, [string | symbol]: any }
        • { foo: number, [string | symbol]: unknown }
        • { foo: number, [any]: any }
        • { foo: number, [any]: unknown }
    • TS Record types
    • Interface extends
    • Flow exact and inexact object types
    • Flow object type spread {| foo: number, ...Bar |}, { foo: number, ...$Exact<Bar>, ... }
    • Class instance types
    • Type aliases
    • Readonly types are converted as-is (but not enforced at runtime, since readonly is strictly a compile-time hint):
      • TS readonly
      • Flow $ReadOnly
      • Flow $ReadOnlyArray
  • Right now the generated validator name is ${typeName}Type and this isn't customizable. In the future I could change it to infer from the starting validator declaration(s).

  • Imports from node_modules aren't currently supported. It may be possible in the future when a package already contains generated validators, and it can find them along with the types in .d.ts or .js.flow files.

CLI

gen-typed-validators <files>

Options:
      --version  Show version number                                   [boolean]
  -q, --quiet    reduce output                                         [boolean]
  -w, --write    write without asking for confirmation                 [boolean]
  -c, --check    check that all validators match types                 [boolean]
      --help     Show help                                             [boolean]

Without the -w or -c option, it will print a diff for any changes it would make, and ask if you want to write the changes.