{"id":22382475,"url":"https://github.com/jcoreio/typescript-validators","last_synced_at":"2025-07-31T03:31:53.643Z","repository":{"id":40781213,"uuid":"278975989","full_name":"jcoreio/typescript-validators","owner":"jcoreio","description":"API input validators with user-friendly error output and TypeScript to ensure you don't miss any properties","archived":false,"fork":false,"pushed_at":"2023-01-05T11:51:57.000Z","size":950,"stargazers_count":12,"open_issues_count":21,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-04-14T22:48:01.910Z","etag":null,"topics":["api","assert","assertion","defensive-programming","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":"2020-07-12T02:22:59.000Z","updated_at":"2023-10-23T04:26:50.000Z","dependencies_parsed_at":"2023-02-04T04:03:30.230Z","dependency_job_id":null,"html_url":"https://github.com/jcoreio/typescript-validators","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Ftypescript-validators","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Ftypescript-validators/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Ftypescript-validators/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Ftypescript-validators/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jcoreio","download_url":"https://codeload.github.com/jcoreio/typescript-validators/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228209939,"owners_count":17885595,"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","js-schema","json","json-schema","object-schema","runtime-types","schema","type","types","typescript","validate","validation","validation-schema","validator"],"created_at":"2024-12-05T00:13:10.453Z","updated_at":"2024-12-05T00:13:11.177Z","avatar_url":"https://github.com/jcoreio.png","language":"TypeScript","readme":"# typescript-validators\n\n[![CircleCI](https://circleci.com/gh/jcoreio/typescript-validators.svg?style=svg)](https://circleci.com/gh/jcoreio/typescript-validators)\n[![Coverage Status](https://codecov.io/gh/jcoreio/typescript-validators/branch/master/graph/badge.svg)](https://codecov.io/gh/jcoreio/typescript-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/typescript-validators.svg)](https://badge.fury.io/js/typescript-validators)\n\nComplex type validators that generate TypeScript types for you.\nThe validation errors are detailed. Adapted from the brilliant work in `flow-runtime`.\n\n# Deprecated\n\nI recreated this project as [`typed-validators`](https://github.com/jcoreio/typed-validators) and added Flow support!\n\nA few breaking changes to the API were necessary for Flow support, but they also made it easier to declare objects with\noptional properties.\n\n# Table of Contents\n\n\u003c!-- toc --\u003e\n\n- [Introduction](#introduction)\n- [What about generating validators from type defs?](#what-about-generating-validators-from-type-defs)\n- [API](#api)\n  - [Type creators](#type-creators)\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.simpleObject({ foo: t.string() })`](#tsimpleobject-foo-tstring-)\n    - [`t.object`](#tobject)\n    - [`t.record(t.string(), t.number())`](#trecordtstring-tnumber)\n    - [`t.instanceOf(Date)`](#tinstanceofdate)\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    - [`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    - [`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 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`typescript-validators` solves this by generating TypeScript types from your validators:\n\n```ts\nimport * as t from 'typescript-validators'\n\nconst PostValidator = t.simpleObject({\n  author: t.simpleObject({\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\n# What about generating validators from type defs?\n\nI'd like to be able to do this, because type defs are a lot more readable. In fact, for Flow, it's possible with\n`babel-pluging-flow-runtime`, which I have a lot of experience with. That looks like this:\n\n```js\nimport {type Type, reify} from 'flow-runtime'\n\ntype Post = {\n  author: {\n    name: string\n    username: string\n  }\n  content: string\n  tags: string[]\n}\n\nconst PostValidator = (reify: Type\u003cPost\u003e) // looooots of magic here\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\nThis is sweet but there are some caveats:\n\n- You have to add a Babel plugin to your toolchain (for TypeScript, not everyone wants to use Babel)\n- There are issues with the Babel plugin. It aims to support all Flow types, with varying success.\n- The original author of `flow-runtime` abandoned the project and I don't blame him. It was hugely ambitious and difficult to maintain.\n\nThe author of `flow-runtime` himself told me in private conversations that he had moved on to an approach like\n`typescript-validators` in his own projects, because generating types from the validator declarations is a lot\nsimpler and more maintainable in the long run.\n\n# API\n\nI recommend importing like this:\n\n```ts\nimport * as t from 'typescript-validators'\n```\n\n## Type creators\n\nAll of the following methods return an instance of `t.Type\u003cT\u003e`.\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\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\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\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.simpleObject({ foo: t.string() })`\n\nA validator that requires the value to be an object with only a `foo` property that's a `string`.\n\n### `t.object`\n\nFor dealing with optional properties, use the following.\nThe syntax is a bit awkward but it's the best way I could find to get a clean type output:\n\n```ts\nconst ThingValidator = t.object\u003c{\n  name: any\n  comment?: any\n}\u003e()({\n  name: t.string(),\n  comment: t.optional(t.string()),\n})\n\ntype Thing = t.ExtractType\u003ctypeof ThingValidator\u003e\n```\n\nThe type of `Thing` will be `{ name: string, comment?: string }`. Note that the property types in the explicit type parameter\n(`any`) are ignored. The type parameter just indicates which properties are required and which are optional, and also allows\nyou to mark properties readonly. These attributes will be reflected in `t.ExtractType`.\n\nYou can also use the `t.optionalNullOr(t.string())` as a shorthand for\n`t.optional(t.nullOr(t.string()))`.\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(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.\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.simpleObject({ name: t.string() })\nconst CommentedType = t.simpleObject({ 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 8 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### `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 'typescript-validators'\n\nconst PostValidator = t.simpleObject({\n  author: t.simpleObject({\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```\nValue must be \u003e 0\n\nExpected: PositiveNumber\n\nActual Value: -1\n\nActual Type: number\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\u003c{\n  value: any\n  left?: any\n  right?: any\n}\u003e()({\n  value: t.any(),\n  left: t.optional(NodeType),\n  right: t.optional(NodeType),\n})\n```\n\nBut `t.optional(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\u003c{\n    value: any\n    left?: any\n    right?: any\n  }\u003e()({\n    value: t.any(),\n    left: t.optional(t.ref(() =\u003e NodeType)),\n    right: t.optional(t.ref(() =\u003e NodeType)),\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%2Ftypescript-validators","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjcoreio%2Ftypescript-validators","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjcoreio%2Ftypescript-validators/lists"}