{"id":20339893,"url":"https://github.com/uditkarode/runtypes","last_synced_at":"2026-06-01T04:32:04.311Z","repository":{"id":107554693,"uuid":"341488871","full_name":"uditkarode/runtypes","owner":"uditkarode","description":null,"archived":false,"fork":false,"pushed_at":"2021-04-11T18:09:19.000Z","size":756,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2026-01-08T17:29:07.781Z","etag":null,"topics":[],"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/uditkarode.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-02-23T08:53:10.000Z","updated_at":"2021-04-11T18:09:21.000Z","dependencies_parsed_at":"2023-06-08T12:00:15.834Z","dependency_job_id":null,"html_url":"https://github.com/uditkarode/runtypes","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/uditkarode/runtypes","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uditkarode%2Fruntypes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uditkarode%2Fruntypes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uditkarode%2Fruntypes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uditkarode%2Fruntypes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/uditkarode","download_url":"https://codeload.github.com/uditkarode/runtypes/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uditkarode%2Fruntypes/sbom","scorecard":{"id":906960,"data":{"date":"2025-08-11","repo":{"name":"github.com/uditkarode/runtypes","commit":"5a0e479b73205e03ba44d28e9a236e30dc3997d3"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":1.7,"checks":[{"name":"Token-Permissions","score":-1,"reason":"No tokens found","details":null,"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Dangerous-Workflow","score":-1,"reason":"no workflows found","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Pinned-Dependencies","score":-1,"reason":"no dependencies found","details":null,"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Code-Review","score":0,"reason":"Found 0/30 approved changesets -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"SAST","score":0,"reason":"no SAST tool detected","details":["Warn: no pull requests merged into dev branch"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: MIT License: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'master'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"Vulnerabilities","score":0,"reason":"26 existing vulnerabilities detected","details":["Warn: Project is vulnerable to: GHSA-968p-4wvh-cqc8","Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92","Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw","Warn: Project is vulnerable to: GHSA-v6h2-p8h4-qcjw","Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg","Warn: Project is vulnerable to: GHSA-w8qv-6jwh-64r5","Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275","Warn: Project is vulnerable to: GHSA-w573-4hg7-7wgq","Warn: Project is vulnerable to: GHSA-fjxv-7rqg-78g4","Warn: Project is vulnerable to: GHSA-43f8-2h32-f4cj","Warn: Project is vulnerable to: GHSA-896r-f27r-55mw","Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h","Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv","Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3","Warn: Project is vulnerable to: GHSA-xvch-5gv4-984h","Warn: Project is vulnerable to: GHSA-5fw9-fq32-wv5p","Warn: Project is vulnerable to: GHSA-hj48-42vr-x3v9","Warn: Project is vulnerable to: GHSA-hrpp-h998-j3pp","Warn: Project is vulnerable to: GHSA-p8p7-x288-28g6","Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw","Warn: Project is vulnerable to: GHSA-jgrx-mgxx-jf9v","Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3","Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7","Warn: Project is vulnerable to: GHSA-6fc8-4gx4-v693","Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q","Warn: Project is vulnerable to: GHSA-p9pc-299p-vxgp"],"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-24T17:41:38.689Z","repository_id":107554693,"created_at":"2025-08-24T17:41:38.690Z","updated_at":"2025-08-24T17:41:38.690Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33760645,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-01T02:00:06.963Z","response_time":115,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":[],"created_at":"2024-11-14T21:18:54.288Z","updated_at":"2026-06-01T04:32:04.294Z","avatar_url":"https://github.com/uditkarode.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Runtypes [![Build Status](https://travis-ci.org/pelotom/runtypes.svg?branch=master)](https://travis-ci.org/pelotom/runtypes) [![Coverage Status](https://coveralls.io/repos/github/pelotom/runtypes/badge.svg?branch=master)](https://coveralls.io/github/pelotom/runtypes?branch=master)\n\n### Safely bring untyped data into the fold\n\nRuntypes allow you to take values about which you have no assurances and check that they conform to some type `A`.\nThis is done by means of composable type validators of primitives, literals, arrays, tuples, records, unions,\nintersections and more.\n\n## Installation\n\n```\nnpm install --save runtypes\n```\n\n## Example\n\nSuppose you have objects which represent asteroids, planets, ships and crew members. In TypeScript, you might write their types like so:\n\n```ts\ntype Vector = [number, number, number];\n\ntype Asteroid = {\n  type: 'asteroid';\n  location: Vector;\n  mass: number;\n};\n\ntype Planet = {\n  type: 'planet';\n  location: Vector;\n  mass: number;\n  population: number;\n  habitable: boolean;\n};\n\ntype Rank = 'captain' | 'first mate' | 'officer' | 'ensign';\n\ntype CrewMember = {\n  name: string;\n  age: number;\n  rank: Rank;\n  home: Planet;\n};\n\ntype Ship = {\n  type: 'ship';\n  location: Vector;\n  mass: number;\n  name: string;\n  crew: CrewMember[];\n};\n\ntype SpaceObject = Asteroid | Planet | Ship;\n```\n\nIf the objects which are supposed to have these shapes are loaded from some external source, perhaps a JSON file, we need to\nvalidate that the objects conform to their specifications. We do so by building corresponding `Runtype`s in a very straightforward\nmanner:\n\n```ts\nimport { Boolean, Number, String, Literal, Array, Tuple, Record, Union } from 'runtypes';\n\nconst Vector = Tuple(Number, Number, Number);\n\nconst Asteroid = Record({\n  type: Literal('asteroid'),\n  location: Vector,\n  mass: Number,\n});\n\nconst Planet = Record({\n  type: Literal('planet'),\n  location: Vector,\n  mass: Number,\n  population: Number,\n  habitable: Boolean,\n});\n\nconst Rank = Union(\n  Literal('captain'),\n  Literal('first mate'),\n  Literal('officer'),\n  Literal('ensign'),\n);\n\nconst CrewMember = Record({\n  name: String,\n  age: Number,\n  rank: Rank,\n  home: Planet,\n});\n\nconst Ship = Record({\n  type: Literal('ship'),\n  location: Vector,\n  mass: Number,\n  name: String,\n  crew: Array(CrewMember),\n});\n\nconst SpaceObject = Union(Asteroid, Planet, Ship);\n```\n\n(See the [examples](examples) directory for an expanded version of this.)\n\nNow if we are given a putative `SpaceObject` we can validate it like so:\n\n```ts\n// spaceObject: SpaceObject\nconst spaceObject = SpaceObject.check(obj);\n```\n\nIf the object doesn't conform to the type specification, `check` will throw an exception.\n\n## Static type inference\n\nIn TypeScript, the inferred type of `Asteroid` in the above example is\n\n```ts\nRuntype\u003c{\n  type: 'asteroid'\n  location: [number, number, number]\n  mass: number\n}\u003e\n```\n\nThat is, it's a `Runtype\u003cAsteroid\u003e`, and you could annotate it as such. But we don't really have to define the\n`Asteroid` type in TypeScript at all now, because the inferred type is correct. Defining each of your types\ntwice, once at the type level and then again at the value level, is a pain and not very [DRY](https://en.wikipedia.org/wiki/Don't_repeat_yourself).\nFortunately you can define a static `Asteroid` type which is an alias to the `Runtype`-derived type like so:\n\n```ts\nimport { Static } from 'runtypes';\n\ntype Asteroid = Static\u003ctypeof Asteroid\u003e;\n```\n\nwhich achieves the same result as\n\n```ts\ntype Asteroid = {\n  type: 'asteroid';\n  location: [number, number, number];\n  mass: number;\n};\n```\n\n## Type guards\n\nIn addition to providing a `check` method, runtypes can be used as [type guards](https://basarat.gitbook.io/typescript/type-system/typeguard):\n\n```ts\nfunction disembark(obj: {}) {\n  if (SpaceObject.guard(obj)) {\n    // obj: SpaceObject\n    if (obj.type === 'ship') {\n      // obj: Ship\n      obj.crew = [];\n    }\n  }\n}\n```\n\n## Pattern matching\n\nThe `Union` runtype offers the ability to do type-safe, exhaustive case analysis across its variants using the `match` method:\n\n```ts\nconst isHabitable = SpaceObject.match(\n  asteroid =\u003e false,\n  planet =\u003e planet.habitable,\n  ship =\u003e true,\n);\n\nif (isHabitable(spaceObject)) {\n  // ...\n}\n```\n\nThere's also a top-level `match` function which allows testing an ad-hoc sequence of runtypes:\n\n```ts\nconst makeANumber = match(\n  [Number, n =\u003e n * 3],\n  [Boolean, b =\u003e b ? 1 : 0],\n  [String, s =\u003e s.length],\n);\n\nmakeANumber(9); // = 27\n```\n\nTo allow the function to be applied to anything and then handle match failures, simply use an `Unknown` case at the end:\n\n```ts\nconst makeANumber = match(\n  [Number, n =\u003e n * 3],\n  [Boolean, b =\u003e b ? 1 : 0],\n  [String, s =\u003e s.length],\n  [Unknown, () =\u003e 42]\n);\n```\n\n## Constraint checking\n\nBeyond mere type checking, we can add arbitrary runtime constraints to a `Runtype`:\n\n```ts\nconst Positive = Number.withConstraint(n =\u003e n \u003e 0);\n\nPositive.check(-3); // Throws error: Failed constraint check\n```\n\nYou can provide more descriptive error messages for failed constraints by returning\na string instead of `false`:\n\n```ts\nconst Positive = Number.withConstraint(n =\u003e n \u003e 0 || `${n} is not positive`);\n\nPositive.check(-3); // Throws error: -3 is not positive\n```\n\nYou can set a custom name for your runtype, which will be used in default error\nmessages and reflection, by using the `name` prop on the optional `options`\nparameter: \n\n```typescript\nconst C = Number.withConstraint(n =\u003e n \u003e 0, {name: 'PositiveNumber'});\n```\n\nTo change the type, there are two ways to do it: passing a type guard function\nto a new `Runtype.withGuard()` method, or using the familiar\n`Runtype.withConstraint()` method. (Both methods also accept an `options`\nparameter to optionally set the name.) \n\nUsing a type guard function is the easiest option to change the static type,\nbecause TS will infer the desired type from the return type of the guard\nfunction.\n\n```typescript\n// use Buffer.isBuffer, which is typed as: isBuffer(obj: any): obj is Buffer;\nconst B = Unknown.withGuard(Buffer.isBuffer);\ntype T = Static\u003ctypeof B\u003e; // T is Buffer\n```\n\nHowever, if you want to return a custom error message from your constraint\nfunction, you can't do this with a type guard because these functions can only\nreturn boolean values.  Instead, you can roll your own constraint function and\nuse the `withConstraint\u003cT\u003e()` method. Remember to specify the type parameter for\nthe `Constraint` because it can't be inferred from your check function!\n\n```typescript\nconst check = (o: any) =\u003e Buffer.isBuffer(o) || 'Dude, not a Buffer!';\nconst B = Unknown.withConstraint\u003cBuffer\u003e(check);\ntype T = Static\u003ctypeof B\u003e; // T will have type of `Buffer`\n```\n\nOne important choice when changing `Constraint` static types is choosing the\ncorrect underlying type. The implementation of `Constraint` will validate the\nunderlying type *before* running your constraint function. So it's important to\nuse a lowest-common-denominator type that will pass validation for all expected\ninputs of your constraint function or type guard.  If there's no obvious\nlowest-common-denominator type, you can always use `Unknown` as the underlying\ntype, as shown in the `Buffer` examples above.  \n\nSpeaking of base types, if you're using a type guard function and your base type\nis `Unknown`, then there's a convenience runtype `Guard` available, which is a\nshorthand for `Unknown.withGuard`.\n\n```typescript\n// use Buffer.isBuffer, which is typed as: isBuffer(obj: any): obj is Buffer;\nconst B = Guard(Buffer.isBuffer);\ntype T = Static\u003ctypeof B\u003e; // T will have type of `Buffer`\n```\n\n## Function contracts\n\nRuntypes along with constraint checking are a natural fit for enforcing function\ncontracts. You can construct a contract from `Runtype`s for the parameters and\nreturn type of the function:\n\n```ts\nconst divide = Contract(\n  // Parameters:\n  Number,\n  Number.withConstraint(n =\u003e n !== 0 || 'division by zero'),\n  // Return type:\n  Number,\n).enforce((n, m) =\u003e n / m);\n\ndivide(10, 2); // 5\n\ndivide(10, 0); // Throws error: division by zero\n```\n\n## Optional values\n\nRuntypes can be used to represent a variable that may be null or undefined\nas well as representing keys within records that may or may not be present.\n\n\n```ts\n// For variables that might be undefined or null\nconst MyString = String;                    // string             (e.g. 'text')\nconst MyStringMaybe = String.Or(Undefined); // string | undefined (e.g. 'text', undefined)\nconst MyStringNullable = String.Or(Null);   // string | null      (e.g. 'text', null)\n```\n\nIf a `Record` may or may not have some keys, we can declare the optional\nkeys using `myRecord.And(Partial({ ... }))`.  Partial keys validate successfully if\nthey are absent or undefined (but not null) or the type specified\n(which can be null).\n\n```ts\n// Using `Ship` from above\nconst RegisteredShip = Ship.And(Record({\n  // All registered ships must have this flag\n  isRegistered: Literal(true),\n})).And(Partial({\n  // We may or may not know the ship's classification\n  shipClass: Union(Literal('military'), Literal('civilian')),\n\n  // We may not know the ship's rank (so we allow it to be undefined via `Partial`),\n  // we may also know that a civilian ship doesn't have a rank (e.g. null)\n  rank: Rank.Or(Null),\n}));\n```\n\nIf a record has keys which _must be present_ but can be null, then use\nthe `Record` runtype normally instead.\n\n```ts\nconst MilitaryShip = Ship.And(Record({\n  shipClass: Literal('military'),\n  \n  // Must NOT be undefined, but can be null\n  lastDeployedTimestamp: Number.Or(Null),\n}));\n```\n\n## Readonly records and arrays\n\nArray and Record runtypes have a special function `.asReadonly()`, that creates a new runtype where the values are readonly.\n\nFor example:\n\n```typescript\nconst Asteroid = Record({\n  type: Literal('asteroid'),\n  location: Vector,\n  mass: Number,\n}).asReadonly()\n\nStatic\u003ctypeof Asteroid\u003e // { readonly type: 'asteroid', readonly location: Vector, readonly mass: number }\n\nconst AsteroidArray = Array(Asteroid).asReadonly()\n\nStatic\u003ctypeof AsteroidArray\u003e // ReadonlyArray\u003cAsteroid\u003e\n```\n\n## Related libraries\n\n* [runtypes-generate](https://github.com/typeetfunc/runtypes-generate) Generates random data by `Runtype` for property-based testing\n* [rest.ts](https://github.com/hmil/rest.ts) Allows building type safe and runtime-checked APIs\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fuditkarode%2Fruntypes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fuditkarode%2Fruntypes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fuditkarode%2Fruntypes/lists"}