{"id":36830812,"url":"https://github.com/zeluisping/itz","last_synced_at":"2026-01-12T14:12:45.579Z","repository":{"id":47993992,"uuid":"196553375","full_name":"zeluisping/itz","owner":"zeluisping","description":"Typescript runtime object type assertion","archived":false,"fork":false,"pushed_at":"2021-08-11T05:59:27.000Z","size":66,"stargazers_count":1,"open_issues_count":3,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-09-26T08:41:54.525Z","etag":null,"topics":["runtime-typechecking","type-safety","typescript","validation"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/itz","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/zeluisping.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-07-12T09:46:08.000Z","updated_at":"2020-03-10T15:48:51.000Z","dependencies_parsed_at":"2022-08-12T16:10:33.382Z","dependency_job_id":null,"html_url":"https://github.com/zeluisping/itz","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/zeluisping/itz","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zeluisping%2Fitz","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zeluisping%2Fitz/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zeluisping%2Fitz/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zeluisping%2Fitz/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zeluisping","download_url":"https://codeload.github.com/zeluisping/itz/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zeluisping%2Fitz/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28340384,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-12T12:22:26.515Z","status":"ssl_error","status_checked_at":"2026-01-12T12:22:10.856Z","response_time":98,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["runtime-typechecking","type-safety","typescript","validation"],"created_at":"2026-01-12T14:12:44.850Z","updated_at":"2026-01-12T14:12:45.565Z","avatar_url":"https://github.com/zeluisping.png","language":"TypeScript","readme":"\u003cdiv align=\"center\"\u003e\n\u003ca href=\"https://github.com/zeluisping/itz\"\u003e\n\n![itz logo](logo.png)\n\u003c/a\u003e\n\n\u003cimg alt=\"NPM\" src=\"https://img.shields.io/npm/l/itz?style=flat-square\"\u003e\n\u003cimg alt=\"npm\" src=\"https://img.shields.io/npm/v/itz?style=flat-square\"\u003e\n\u003cimg alt=\"npm type definitions\" src=\"https://img.shields.io/npm/types/itz?style=flat-square\"\u003e\n\u003cimg alt=\"npm dev dependency version\" src=\"https://img.shields.io/npm/dependency-version/itz/dev/typescript?style=flat-square\"\u003e\n\u003c/div\u003e\n\u003cbr/\u003e\n\n`itz` is a TypeScript library for performing runtime object type validation, while offering correct intellisense, it allows you to write custom type validations, giving you the hability to validate complex type structures.\n\nBesides being able to validate fields, you can also mutate them, and even give back a completely different type from what came in.\n\nIf you really wanted you could even go as far as making HTTP requests (or anything else really) inside a validator and use the result of such an operation as the validated value. For cases like this don't forget that any time spent doing such extra work is extra time spent validating the object. Also when any field fails validation, all previous already validated fields are discarded, throwing away any extra fancy processing you may want to perform.\n\n# Index\n\n-   [Example Usage](#Example-Usage)\n-   [Custom Validators](#Custom-Validators)\n-   [itz.A](#itz.A)\n-   [Constants](#Constants)\n    -   [InvalidValue](#InvalidValue)\n    -   [OptionalValue](#OptionalValue)\n-   [Validators](#Validators)\n    -   [Primitives](#Primitive-Validators)\n        -   [itz.Boolean](#itz.Boolean)\n        -   [itz.Number](#itz.Number)\n        -   [itz.String](#itz.String)\n        -   [itz.Object](#itz.Object)\n        -   [itz.Null](#itz.Null)\n        -   [itz.Undefined](#itz.Undefined)\n        -   [itz.Any](#itz.Any)\n    -   [Converters](#Converters)\n        -   [itz.AsBoolean](#itz.AsBoolean)\n        -   [itz.AsDate](#itz.AsNumber)\n        -   [itz.AsNumber](#itz.AsString)\n        -   [itz.AsString](#itz.AsObject)\n    -   [Generics](#Generics)\n        -   [itz.Default](#itz.Default)\n        -   [itz.Either](#itz.Either)\n        -   [itz.Optional](#itz.Optional)\n\n# Example Usage\n\nA simple example usege would be performing validation on request data.\n\nFor example, here we quickly validate `req.params` to ensure it matches the structure we want. In this case we'll be wanting two fields:\n\n-   `name` that **must** be a `string`\n-   `age` that should be convertible to a `number` and if not then `undefined` (for being optional)\n\n```typescript\nimport { Router } from 'express';\nimport itz from 'itz';\n\nconst router = Router();\nexport default router;\n\nconst GreetParams = itz.A({\n    name: itz.String,\n    age: itz.AsOptionalNumber, // same as: itz.Optional(itz.AsNumber)\n});\n\nrouter.use('/greet/:name/:age?', (req, res) =\u003e {\n    const params = GreetParams(req.params);\n    if (typeof params === 'undefined') {\n        res.status(401).send('Have you been drinking?');\n        return;\n    }\n    if (typeof params.age === 'undefined') {\n        res.status(200).send(`Hello there ${params.name}! How old are you?`);\n        return;\n    }\n    if (params.age \u003c 18) {\n        res.status(403).send(`You're too young to be here ${params.name}!`);\n        return;\n    }\n    res.status(200).send(`Hello there ${params.name}! You're ${params.age}, not too shabby.`);\n});\n```\n\nHere the declared local variable `params` is of the type `undefined | { name: string, age: number | undefined }`. If validation fails `undefined` is returned, otherwise it returns the new validated object.\n\n# Custom Validators\n\nThe signature of a validator must comply with the type `Validator`\nAll you need to write a custom validator is to create a function that follows the type `Validator`. Following is an example validator that validates a string literal type union:\n\n```typescript\nimport { InvalidValue, ValidatorReturn } from 'itz';\n\nexport type ESpan = 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly';\nfunction isESpan(x: any): x is ESpan {\n    switch (x) {\n        case 'hourly':\n        case 'daily':\n        case 'weekly':\n        case 'monthly':\n        case 'yearly':\n            return true;\n        default:\n    }\n    return false;\n}\n\nexport function itzESpan(key: string, value: any): ValidatorReturn\u003cESpan\u003e {\n    if (isESpan(value) === true) {\n        return [true, value];\n    }\n    return InvalidValue;\n}\n```\n\nThe way a validator is written, allows us to do post processing on the value before returning it into the final object. With this you can also do more advanced processing of any kind; you can go as crazy as making an HTTP request to a remote server for retrieving a default value, anything goes. When doing such crazy things remember that if a field further ahead, from the one your validator is currently working on, fails to be validated, the whole partial object that had already been validated will be discarded as the main porpuse of this library is to validate the object against the whole wanted structure.\n\nThe return type of a validator is a tuple with either of the forms:\n\n-   `[false]` on failure (use constant `InvalidValue`)\n-   `[false,undefined]` **@deprecated** alias for `[false]`\n-   `[true, T]` on success where `T` is the type you're validating\n\nFor simplicity, checkout [Constants](#Constants)\n\n-   the first element is the `ok` flag; `true` means validated and `false` means failure\n-   the second element has two options\n    -   when `ok === false` it **must** be `undefined`\n    -   of type `T` (the type you're validating) when `ok === true`; alternative to doing `return [false,undefined]`, creating tuples all the time, you can just use the constant `return itz.INVALID_VALUE`. For optional validators instead of always having do do `return [true,undefined]`, also creating tuples all time, you can just do `return itz.OPTIONAL_DEFAULT`.\n\nThe key being validated is provided for any case where it might be useful, only the keys from the given structure are validated, any extra keys the object being validated might have are just ignored.\n\n# itz.A\n\nThis function is what constructors a validator from a structure you define. The constructed validator takes in any object whose type extends `{ [K: string]: any }` and either returns the validated object with the correct type derived from the structure, or `undefined` if validation failed.\n\n## Signature\n\n```typescript\nA\u003cT extends IStructure\u003e(\n        structure: T,\n    ): (what: { [K: string]: any }) =\u003e { [K in keyof T]: ValidatorType\u003cT[K]\u003e } | undefined\n```\n\n## Example\n\nAn example usage of this function can be seen in [Usage Example]\u003c(#Usage-Example).\n\n# Constants\n\nTo aid in the creation of custom validators, a few constants where created for common validation results.\n\n### InvalidValue\n\nDefined simply as `readonly [false]` this constant can be used by validators when validation fails, making it more expressive.\n\n### OptionalValue\n\nDefined simply as `readonly [true, undefined]` this constant is meant to be used with optional validators, when validation fails and so the fallback optional value `undefined` is used.\n\n# Validators\n\nValidators are the foundation of this library, as they are the ones in charge of all the type checking, value conversions and what not.\n\n## Primitives\n\nPrimitives directly represent the primitives of the language. They're the most strict type of validators as the input value must have exactly the type we want, and nothing more.\n\nFor each of these primitives there is an optional version with the naming convention `itz.OptionalTYPE`; each of them is equivalente to `itz.Optional(itz.TYPE)`.\n\n### itz.Boolean\n\nThis validator ensures that the type of the value is specifically `boolean`, failing if not.\n\nA field that passes this validation will have the type `boolean`.\n\n### itz.Number\n\nThis validator ensures that the type of the value is specifically `number`, failing if not.\n\nA field that passes this validation will have the type `number`.\n\n### itz.String\n\nThis validator ensures that the type of the value is specifically `string`, failing if not.\n\nA field that passes this validation will have the type `string`.\n\n### itz.Object\n\nThis validator ensures that the type of the value is specifically `object`, failing if not. Despite that `typeof null === 'object'`, this validator does not consider `null` to be a valid value.\n\nA field that passes this validation will have the type `object`.\n\n### itz.Null\n\nThis validator ensures that the value is specifically `null`, failing if not.\n\nA field that passes this validation will have the type `null`.\n\n### itz.Undefined\n\nThis validator ensures the value is specifically `undefined`, failing if not.\n\nA field that passes this validation will have the type `undefined`.\n\n### itz.Any\n\nThis validator always passes. The resulting field will be of type `any`.\n\n## Converters\n\nConverters are a _special_ kind of validators. Well not really special as both have the same signatures and a similar porpuse. The difference being that these validators usually give back a completely new value derived from the original.\n\nFor each of these converters there is an optional version with the naming convention `itz.AsOptionalTYPE`; each of them is equivalente to `itz.Optional(itz.AsTYPE)`.\n\n### itz.AsBoolean\n\nAttempts to convert the value to a `boolean`, failing if not known how.\n\nConversions are possible from the following types:\n\n-   `boolean` (no conversion)\n-   `number`\n    -   `false` when `0`\n    -   `true` when anything but `0`\n-   `string`\n    -   `true` when `\"1\"` or `\"true\"`\n    -   `false` when `\"0\"` or `\"false\"`\n\nA field that passes this validation will have the type `boolean`.\n\n### itz.AsDate\n\nAttempts to convert the value to a `Date`, failing if not known how.\n\nConversions are possible from the following types:\n\n-   `Date` (no conversion)\n-   `number` [@see Unix Timestamp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Unix_timestamp)\n    \u003e An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the Unix epoch), with leap seconds ignored.\n-   `string` [@see Timestamp String]()\n    \u003e A string value representing a date, specified in a format recognized by the [Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) method ...\n\nA field that passes this validation will have the type `Date`.\n\n### itz.AsNumber\n\nAttempts to convert the value to a `number`, failing if not known how.\n\nConversions are possible from the following types:\n\n-   `number` (no conversion)\n-   `string` fails if not a number representation (**NaN**)\n-   `boolean`\n    -   `1` when `true`\n    -   `0` when `false`\n\nA field that passes this validation will have the type `number`.\n\n### itz.AsString\n\nAttempts to convert the value to a `string`, failing if not known how.\n\nConversions are possible from the following types:\n\n-   `string` (no conversion)\n-   `number` (string representation of the number)\n-   `boolean`\n    -   `\"true\"` when `true`\n    -   `\"false\"` when `false`\n\nA field that passes this validation will have the type `string`.\n\n## Generics\n\nThe porpuse of these generics is to give you a lot more flexibility in defining your validation structures. Since they're generic, they can be used together with other kinds of validators as to compose a new type validation. Essentially they are but different composition methods.\n\n### itz.Default\n\nThis generic makes any other validator always have a fallback value, taking over validators that result in either an [`InvalidValue`](#InvalidValue) or [`OptionalValue`](#OptionalValue). This means any field with a default will never fail nor have the type `undefined`.\n\n#### Signature\n\n```typescript\nfunction \u003cT, X extends Exclude\u003cT, undefined\u003e\u003e(\n    validator: Validator\u003cT\u003e,\n    Default: X,\n)\n```\n\nAny field with this generic is guaranteed to always return the value of type `T` (the type being validated).\n\n### itz.Either\n\nThis generic allows you to validate against multiple types, imagine of it as something like a type `union`.\n\n#### Signature\n\n```typescript\n// Some helping types\ntype ValidatorArray\u003cT extends any\u003e = Array\u003cValidator\u003cT\u003e\u003e;\ntype ValidatorArrayInfer\u003cT extends ValidatorArray\u003cany\u003e\u003e = T extends ValidatorArray\u003cinfer R\u003e ? R : never;\n\n// The actual signature\nitzEither\u003cR extends ValidatorArray\u003cany\u003e\u003e(...rest: R): Validator\u003cValidatorArrayInfer\u003cR\u003e\u003e\n```\n\nAny field with this genric will return any of the value types the given validators give back. Thus having a field with `itz.Either(itz.String, itz.Number)` will result in a value of type `string | number`.\n\n### itz.Optional\n\nThis genric allows you to represent an optional field; it never fails as it always fallsback to a default value `undefined`.\n\n#### Signature\n\n```typescript\nitzOptional\u003cT\u003e(validator: Validator\u003cT\u003e): Validator\u003cT | undefined\u003e\n```\n\nThe resulting value type for a field with a `itz.Optional` is always either the value type for the given validator or undefined.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzeluisping%2Fitz","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzeluisping%2Fitz","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzeluisping%2Fitz/lists"}