{"id":21121508,"url":"https://github.com/jcoreio/typed-validators","last_synced_at":"2025-07-22T15:33:55.600Z","repository":{"id":52862410,"uuid":"326074241","full_name":"jcoreio/typed-validators","owner":"jcoreio","description":"complex type validators that generate TypeScript and Flow types for you","archived":false,"fork":false,"pushed_at":"2022-09-21T21:47:01.000Z","size":603,"stargazers_count":8,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-06-27T07:08:48.779Z","etag":null,"topics":["api","assert","assertion","defensive-programming","flow","flowtype","js-schema","json","json-schema","object-schema","runtime-types","schema","type","types","typescript","validate","validation","validation-schema","validator"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jcoreio.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-01-01T23:34:19.000Z","updated_at":"2024-12-18T01:16:48.000Z","dependencies_parsed_at":"2022-09-15T08:20:53.833Z","dependency_job_id":null,"html_url":"https://github.com/jcoreio/typed-validators","commit_stats":null,"previous_names":[],"tags_count":25,"template":false,"template_full_name":null,"purl":"pkg:github/jcoreio/typed-validators","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Ftyped-validators","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Ftyped-validators/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Ftyped-validators/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Ftyped-validators/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jcoreio","download_url":"https://codeload.github.com/jcoreio/typed-validators/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Ftyped-validators/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263806772,"owners_count":23514441,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","assert","assertion","defensive-programming","flow","flowtype","js-schema","json","json-schema","object-schema","runtime-types","schema","type","types","typescript","validate","validation","validation-schema","validator"],"created_at":"2024-11-20T03:50:59.045Z","updated_at":"2025-07-22T15:33:55.446Z","avatar_url":"https://github.com/jcoreio.png","language":"TypeScript","readme":"# typed-validators\n\n[![CircleCI](https://circleci.com/gh/jcoreio/typed-validators.svg?style=svg)](https://circleci.com/gh/jcoreio/typed-validators)\n[![Coverage Status](https://codecov.io/gh/jcoreio/typed-validators/branch/master/graph/badge.svg)](https://codecov.io/gh/jcoreio/typed-validators)\n[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)\n[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)\n[![npm version](https://badge.fury.io/js/typed-validators.svg)](https://badge.fury.io/js/typed-validators)\n\nComplex type validators that generate TypeScript or Flow types for you.\nThe validation errors are detailed. Adapted from the brilliant work in `flow-runtime`.\n\n# Table of Contents\n\n\u003c!-- toc --\u003e\n\n- [typed-validators](#typed-validators)\n- [Table of Contents](#table-of-contents)\n- [Introduction](#introduction)\n- [Limitations](#limitations)\n- [Generating validators from type defs](#generating-validators-from-type-defs)\n  - [Before](#before)\n  - [Command](#command)\n  - [After](#after)\n- [API](#api)\n  - [Type creators](#type-creators)\n    - [`t.any()`](#tany)\n    - [`t.unknown()`](#tunknown)\n    - [`t.boolean()`](#tboolean)\n    - [`t.boolean(true)`](#tbooleantrue)\n    - [`t.string()`](#tstring)\n    - [`t.string('foo')`](#tstringfoo)\n    - [`t.number()`](#tnumber)\n    - [`t.number(3)`](#tnumber3)\n    - [`t.symbol()`](#tsymbol)\n    - [`t.symbol(MySymbol)`](#tsymbolmysymbol)\n    - [`t.null()` / `t.nullLiteral()`](#tnull--tnullliteral)\n    - [`t.nullOr(t.string())`](#tnullortstring)\n    - [`t.undefined()` / `t.undefinedLiteral()`](#tundefined--tundefinedliteral)\n    - [`t.nullish()`](#tnullish)\n    - [`t.nullishOr(t.string())`](#tnullishortstring)\n    - [`t.array(t.number())`](#tarraytnumber)\n    - [`t.readonlyArray(t.number())`](#treadonlyarraytnumber)\n    - [`t.object(properties)`](#tobjectproperties)\n    - [`t.object({ required?, optional?, exact? })`](#tobject-required-optional-exact-)\n    - [`t.opaque\u003cDateString\u003e(() =\u003e t.string())`](#topaquedatestring--tstring)\n    - [`t.readonly(objectType)`](#treadonlyobjecttype)\n    - [`t.merge(...objectTypes)`](#tmergeobjecttypes)\n    - [`t.mergeInexact(...objectTypes)`](#tmergeinexactobjecttypes)\n    - [`t.record(t.string(), t.number())`](#trecordtstring-tnumber)\n    - [`t.instanceOf(() =\u003e Date)`](#tinstanceof--date)\n    - [`t.tuple(t.string(), t.number())`](#ttupletstring-tnumber)\n    - [`t.allOf(A, B)`](#tallofa-b)\n    - [`t.oneOf(t.string(), t.number())`](#toneoftstring-tnumber)\n    - [`t.alias(name, type)`](#taliasname-type)\n    - [`t.ref(() =\u003e typeAlias)`](#tref--typealias)\n  - [`t.Type\u003cT\u003e`](#ttypet)\n    - [`accepts(input: any): boolean`](#acceptsinput-any-boolean)\n    - [`acceptsSomeCompositeTypes: boolean (getter)`](#acceptssomecompositetypes-boolean-getter)\n    - [`assert\u003cV extends T\u003e(input: any, prefix = '', path?: (string | number | symbol)[]): V`](#assertv-extends-tinput-any-prefix---path-string--number--symbol-v)\n    - [`validate(input: any, prefix = '', path?: (string | number | symbol)[]): Validation\u003cT\u003e`](#validateinput-any-prefix---path-string--number--symbol-validationt)\n    - [`warn(input: any, prefix = '', path?: (string | number | symbol)[]): void`](#warninput-any-prefix---path-string--number--symbol-void)\n    - [`toString(): string`](#tostring-string)\n  - [`t.ExtractType\u003cT extends Type\u003cany\u003e\u003e`](#textracttypet-extends-typeany)\n  - [`t.TypeAlias\u003cT\u003e`](#ttypealiast)\n    - [`readonly name: string`](#readonly-name-string)\n    - [`addConstraint(...constraints: TypeConstraint\u003cT\u003e[]): this`](#addconstraintconstraints-typeconstraintt-this)\n  - [Custom Constraints](#custom-constraints)\n  - [Recursive Types](#recursive-types)\n\n\u003c!-- tocstop --\u003e\n\n# Introduction\n\nWhen you need to validate the inputs to a TypeScript or Flow API, a problem arises. How do you ensure that a value that passes validation\nmatches your declared TypeScript type? Someone might modify one and forget to modify the other:\n\n```ts\ntype Post = {\n  author: {\n    name: string\n    username: string\n  }\n  content: string\n  // newly added by developer\n  tags: string[]\n}\n\n// hypothetical syntax\nconst validator = requireObject({\n  author: requireObject({\n    name: requireString(),\n    username: requireString(),\n  }),\n  content: requireString(),\n  // uhoh!! developer forgot to add tags here\n})\n```\n\n`typed-validators` solves this by generating TypeScript or Flow types from your validators:\n\n```ts\nimport * as t from 'typed-validators'\n\nconst PostValidator = t.object({\n  author: t.object({\n    name: t.string(),\n    username: t.string(),\n  }),\n  content: t.string(),\n  tags: t.array(t.string()),\n})\n\ntype Post = t.ExtractType\u003ctypeof PostValidator\u003e\n\nconst example: Post = PostValidator.assert({\n  author: {\n    name: 'MC Hammer',\n    username: 'hammertime',\n  },\n  content: \"Can't touch this\",\n  tags: ['mc-hammer', 'hammertime'],\n})\n```\n\nHover over `Post` in VSCode and you'll see, voilà:\n\n```ts\ntype Post = {\n  author: {\n    name: string\n    username: string\n  }\n  content: string\n  tags: string[]\n}\n```\n\nExample error message:\n\n```ts\nPostValidator.assert({\n  author: {\n    name: 'MC Hammer',\n    usernme: 'hammertime',\n  },\n  content: 1,\n  tags: ['mc-hammer', { tag: 'hammertime' }],\n})\n```\n\n```\nRuntimeTypeError: input.author is missing required property username, which must be a string\n\nActual Value: {\n  name: \"MC Hammer\",\n  usernme: \"hammertime\",\n}\n\n-------------------------------------------------\n\ninput.author has unknown property: usernme\n\nActual Value: {\n  name: \"MC Hammer\",\n  usernme: \"hammertime\",\n}\n\n-------------------------------------------------\n\ninput.content must be a string\n\nActual Value: 1\n\n-------------------------------------------------\n\ninput.tags[1] must be a string\n\nActual Value: {\n  tag: \"hammertime\",\n}\n```\n\n# Limitations\n\n- Flow seems to suck at fully resolving `t.ExtractType\u003c...\u003e` for deeply nested object types. Past a certain level of complexity\n  it seems to give up and use `any` for some object-valued properties. That's why I created [`gen-typed-validators`](https://github.com/jcoreio/gen-typed-validators),\n  so that you can control the type definitions and generate `typed-validators` from them.\n- Generic types aren't supported. I may add support for it in the future if I'm confident I can make a robust implementation.\n- Function types aren't supported. You can use `t.instanceOf(() =\u003e Function)`, but Flow treats the `Function` type as `any`. I may add `t.function()` in the future, but\n  it won't validate argument or return types, because those can't be determined from function instances at runtime.\n- The goal is to support a subset of types common to TS and Flow well, rather than support every possible complex derived type\n  you can make. (That's what `babel-plugin-flow-runtime` basically tried to do, and it was too ambitious. I created this so that I could\n  stop using it.)\n\n# Generating validators from type defs\n\nThis is now possible with [`gen-typed-validators`](https://github.com/jcoreio/gen-typed-validators)!\n\nIt creates or replaces validators anywhere you declare a variable of type `t.TypeAlias`:\n\n### Before\n\n```ts\n// Post.ts\nimport * as t from 'typed-validators'\n\ntype Author = {\n  name: string\n  username: string\n}\n\nexport type Post = {\n  author: Author\n  content: string\n  tags: string[]\n}\n\nexport const PostType: t.TypeAlias\u003cPost\u003e = null\n```\n\n### Command\n\n```sh\n$ gen-typed-validators Post.ts\n```\n\n### After\n\n```ts\n// Post.ts\nimport * as t from 'typed-validators'\n\nexport type Author = {\n  name: string\n  username: string\n}\n\nconst AuthorType: t.TypeAlias\u003cAuthor\u003e = t.alias(\n  'Author',\n  t.object({\n    name: t.string(),\n    username: t.string(),\n  })\n)\n\nexport type Post = {\n  author: Author\n  content: string\n  tags: string[]\n}\n\nexport const PostType: t.TypeAlias\u003cPost\u003e = t.alias(\n  'Post',\n  t.object({\n    author: t.ref(() =\u003e AuthorType),\n    content: t.string(),\n    tags: t.array(t.string()),\n  })\n)\n```\n\n# API\n\nI recommend importing like this:\n\n```ts\nimport * as t from 'typed-validators'\n```\n\n## Type creators\n\nAll of the following methods return an instance of `t.Type\u003cT\u003e`.\n\n### `t.any()`\n\nA validator that accepts any value.\n\n### `t.unknown()`\n\nA validator that accepts any value but has TS `unknown` type/Flow `mixed` type.\n\n### `t.boolean()`\n\nA validator that requires the value to be a `boolean`.\n\n### `t.boolean(true)`\n\nA validator that requires the value to be `true`.\n\nNote: to get the proper Flow types, you'll unforunately have to do `t.boolean\u003ctrue\u003e(true)`.\n\n### `t.string()`\n\nA validator that requires the value to be a `string`.\n\n### `t.string('foo')`\n\nA validator that requires the value to be `'foo'`.\n\nNote: to get the proper Flow types, you'll unfortunately have to do `t.string\u003c'foo'\u003e('foo')`.\n\n### `t.number()`\n\nA validator that requires the value to be a `number`.\n\n### `t.number(3)`\n\nA validator that requires the value to be `3`.\n\nNote: to get the proper Flow types, you'll unfortunately have to do `t.number\u003c3\u003e(3)`.\n\n### `t.symbol()`\n\nA validator that requires the value to be a `symbol`.\n\n### `t.symbol(MySymbol)`\n\nA validator that requires the value to be `MySymbol`.\n\n### `t.null()` / `t.nullLiteral()`\n\nA validator that requires the value to be `null`.\n\n### `t.nullOr(t.string())`\n\nA validator that requires the value to be `string | null`\n\n### `t.undefined()` / `t.undefinedLiteral()`\n\nA validator that requires the value to be `undefined`.\n\n### `t.nullish()`\n\nA validator that requires the value to be `null | undefined`.\n\n### `t.nullishOr(t.string())`\n\nA validator that requires the value to be `string | null | undefined`.\n\n### `t.array(t.number())`\n\nA validator that requires the value to be `number[]`.\n\n### `t.readonlyArray(t.number())`\n\nA validator that requires the value to be `number[]`.\nDoesn't require the value to be frozen; just allows the extracted type to be `ReadonlyArray`.\n\n### `t.object(properties)`\n\nA validator that requires the value to be an object with all of the given required properties an no additional properties.\n\nFor example:\n\n```ts\nconst PersonType = t.object({\n  name: t.string(),\n  age: t.number(),\n})\n\nPersonType.assert({ name: 'dude', age: 100 }) // ok\nPersonType.assert({ name: 'dude' }) // error\nPersonType.assert({ name: 1, age: 100 }) // error\nPersonType.assert({ name: 'dude', age: 100, powerLevel: 9000 }) // error\n```\n\n### `t.object({ required?, optional?, exact? })`\n\nA validator that requires the value to be an object with given properties.\nAdditional properties won't be allowed unless `exact` is `false`.\n\nFor example:\n\n```ts\nconst PersonType = t.object({\n  required: {\n    name: t.string(),\n  },\n  optional: {\n    age: t.number(),\n  },\n})\n\nPersonType.assert({ name: 'dude' }) // ok\nPersonType.assert({ name: 'dude', age: 100 }) // ok\nPersonType.assert({ name: 1 }) // error\nPersonType.assert({ name: 'dude', age: 'old' }) // error\n```\n\n### `t.opaque\u003cDateString\u003e(() =\u003e t.string())`\n\nA validator that requires the value to be a string, but presents the type as `DateString` (for instance with `export opaque type DateString = string`)\n\n### `t.readonly(objectType)`\n\nUse `t.readonly(t.object(...))` or `t.readonly(t.merge(...))` etc. Doesn't require the object to be frozen, just allows the extracted type to be readonly.\n\n### `t.merge(...objectTypes)`\n\nMerges the properties of multiple object validators together into an exact object validator (no additional properties are allowed).\n\nNote: merging `t.alias`es and `t.ref`s that resolve to object validators is supported, but any constraints on the referenced aliases won't be applied.\n\nFor example:\n\n```ts\nconst PersonType = t.object({\n  required: {\n    name: t.string(),\n  },\n  optional: {\n    age: t.number(),\n  },\n})\nconst AddressType = t.object({\n  street: t.string(),\n  city: t.string(),\n  state: t.string(),\n  zip: t.string(),\n})\n\nconst PersonWithAddressType = t.merge(PersonType, AddressType)\n\nPersonWithAddressType.assert({\n  // ok\n  name: 'dude',\n  age: 100,\n  street: 'Bourbon Street',\n  city: 'New Orleans',\n  zip: '77777',\n})\n```\n\n### `t.mergeInexact(...objectTypes)`\n\nMerges the properties of multiple object validators together into an inexact object validator (additional properties are allowed).\n\nNote: merging `t.alias`es and `t.ref`s that resolve to object validators is supported, but any constraints on the referenced aliases won't be applied.\n\nAccepts a variable number of arguments, though type generation is only overloaded up to 8 arguments.\nAccepts a variable number of arguments, though type generation is only overloaded up to 8 arguments.\n\n### `t.record(t.string(), t.number())`\n\nA validator that requires the value to be `Record\u003cstring, number\u003e`.\n\n### `t.instanceOf(() =\u003e Date)`\n\nA validator that requires the value to be an instance of `Date`.\n\n### `t.tuple(t.string(), t.number())`\n\nA validator that requires the value to be `[string, number]`.\nAccepts a variable number of arguments, though type generation for Flow is only overloaded up to 8 arguments.\n\n### `t.allOf(A, B)`\n\nA validator that requires the value to be `A \u0026 B`. Accepts a variable number of arguments, though type generation is only overloaded up to 8 arguments. For example:\n\n```ts\nconst ThingType = t.object({ name: t.string() })\nconst CommentedType = t.object({ comment: t.string() })\n\nconst CommentedThingType = t.allOf(ThingType, CommentedType)\n\nCommentedThingType.assert({ name: 'foo', comment: 'sweet' })\n```\n\n### `t.oneOf(t.string(), t.number())`\n\nA validator that requires the value to be `string | number`. Accepts a variable number of arguments, though type generation is only overloaded up to 32 arguments.\n\n### `t.alias(name, type)`\n\nCreates a `TypeAlias` with the given `name` and `type`.\n\nType aliases serve two purposes:\n\n- They allow you to [create recursive type validators with `t.ref()`](#recursive-types)\n- You can [add custom constraints to them](#custom-constraints)\n\n### `t.ref(() =\u003e typeAlias)`\n\nCreates a reference to the given `TypeAlias`. See [Recursive Types](#recursive-types) for examples.\n\n## `t.Type\u003cT\u003e`\n\nThe base class for all validator types.\n\n`T` is the type of values it accepts.\n\n### `accepts(input: any): boolean`\n\nReturns `true` if and only if `input` is the correct type.\n\n### `acceptsSomeCompositeTypes: boolean (getter)`\n\nReturns `true` if the validator accepts some values that are not primitives, null or undefined.\n\n### `assert\u003cV extends T\u003e(input: any, prefix = '', path?: (string | number | symbol)[]): V`\n\nThrows an error if `input` isn't the correct type.\n\n`prefix` will be prepended to thrown error messages.\n\n`path` will be prepended to validation error paths. If you are validating a function parameter named `foo`,\npass `['foo']` for `path` to get clear error messages.\n\n### `validate(input: any, prefix = '', path?: (string | number | symbol)[]): Validation\u003cT\u003e`\n\nValidates `input`, returning any errors in the `Validation`.\n\n`prefix` and `path` are the same as in `assert`.\n\n### `warn(input: any, prefix = '', path?: (string | number | symbol)[]): void`\n\nLogs a warning to the console if `input` isn't the correct type.\n\n### `toString(): string`\n\nReturns a string representation of this type (using TS type syntax in most cases).\n\n## `t.ExtractType\u003cT extends Type\u003cany\u003e\u003e`\n\nGets the TypeScript type that a validator type accepts. For example:\n\n```ts\nimport * as t from 'typed-validators'\n\nconst PostValidator = t.object({\n  author: t.object({\n    name: t.string(),\n    username: t.string(),\n  }),\n  content: t.string(),\n  tags: t.array(t.string()),\n})\n\ntype Post = t.ExtractType\u003ctypeof PostValidator\u003e\n```\n\nHover over `Post` in the IDE and you'll see, voilà:\n\n```ts\ntype Post = {\n  author: {\n    name: string\n    username: string\n  }\n  content: string\n  tags: string[]\n}\n```\n\n## `t.TypeAlias\u003cT\u003e`\n\n### `readonly name: string`\n\nThe name of the alias.\n\n### `addConstraint(...constraints: TypeConstraint\u003cT\u003e[]): this`\n\nAdds custom constraints. `TypeConstraint\u003cT\u003e` is a function `(value: T) =\u003e string | null | undefined` which\nreturns nullish if `value` is valid, or otherwise a `string` describing why `value` is invalid.\n\n## Custom Constraints\n\nIt's nice to be able to validate that something is a `number`, but what if we want to make sure it's positive?\nWe can do this by creating a type alias for `number` and adding a custom constraint to it:\n\n```ts\nconst PositiveNumberType = t\n  .alias('PositiveNumber', t.number())\n  .addConstraint((value: number) =\u003e (value \u003e 0 ? undefined : 'must be \u003e 0'))\n\nPositiveNumberType.assert(-1)\n```\n\nThe assertion will throw a `t.RuntimeTypeError` with the following message:\n\n```\ninput must be \u003e 0\n\nActual Value: -1\n```\n\n## Recursive Types\n\nCreating validators for recursive types takes a bit of extra effort. Naively, we would want to do this:\n\n```ts\nconst NodeType = t.object({\n  required: {\n    value: t.any(),\n  },\n  optional: {\n    left: NodeType,\n    right: NodeType,\n  },\n})\n```\n\nBut `left: NodeTYpe` causes the error `Block-scoped variable 'NodeType' referenced before its declaration`.\n\nTo work around this, we can create a `TypeAlias` and a reference to it:\n\n```ts\nconst NodeType: t.TypeAlias\u003c{\n  value: any\n  left?: Node\n  right?: Node\n}\u003e = t.alias(\n  'Node',\n  t.object({\n    required: {\n      value: t.any(),\n    },\n    optional: {\n      left: t.ref(() =\u003e NodeType),\n      right: t.ref(() =\u003e NodeType),\n    },\n  })\n)\n\ntype Node = t.ExtractType\u003ctypeof NodeType\u003e\n\nNodeType.assert({\n  value: 'foo',\n  left: {\n    value: 2,\n    right: {\n      value: 3,\n    },\n  },\n  right: {\n    value: 6,\n  },\n})\n```\n\nNotice how we use a thunk function in `t.ref(() =\u003e NodeType)` to avoid referencing `NodeType` before its declaration.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjcoreio%2Ftyped-validators","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjcoreio%2Ftyped-validators","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjcoreio%2Ftyped-validators/lists"}