runtypes
- Version 6.7.0
- Published
- 124 kB
- No dependencies
- MIT license
Install
npm i runtypes
yarn add runtypes
pnpm add runtypes
Overview
Runtime validation for static types
Index
Variables
Functions
Classes
Interfaces
Type Aliases
Variables
variable BigInt
const BigInt: BigInt;
Validates that a value is a bigint.
variable Boolean
const Boolean: boolean;
Validates that a value is a boolean.
variable Failcode
const Failcode: { readonly TYPE_INCORRECT: 'TYPE_INCORRECT'; readonly VALUE_INCORRECT: 'VALUE_INCORRECT'; readonly KEY_INCORRECT: 'KEY_INCORRECT'; readonly CONTENT_INCORRECT: 'CONTENT_INCORRECT'; readonly ARGUMENT_INCORRECT: 'ARGUMENT_INCORRECT'; readonly RETURN_INCORRECT: 'RETURN_INCORRECT'; readonly CONSTRAINT_FAILED: 'CONSTRAINT_FAILED'; readonly PROPERTY_MISSING: 'PROPERTY_MISSING'; readonly PROPERTY_PRESENT: 'PROPERTY_PRESENT'; readonly NOTHING_EXPECTED: 'NOTHING_EXPECTED';};
variable Function
const Function: Function;
Construct a runtype for functions.
variable Never
const Never: Never;
Validates nothing (unknown fails).
variable Null
const Null: Literal<null>;
An alias for Literal(null).
variable Nullish
const Nullish: Union<[Literal<null>, Literal<undefined>]>;
An alias for
Union(Null, Undefined)
.
variable Number
const Number: number;
Validates that a value is a number.
variable RuntypeName
const RuntypeName: Symbol;
variable String
const String: string;
Validates that a value is a string.
variable Symbol
const Symbol: Symbol;
Validates that a value is a symbol, regardless of whether it is keyed or not.
variable Undefined
const Undefined: Literal<undefined>;
An alias for Literal(undefined).
variable Unknown
const Unknown: Unknown;
Validates anything, but provides no new type information about it.
variable Void
const Void: Unknown;
Void is an alias for Unknown
Deprecated
Please use Unknown instead
Functions
function Array
Array: <E extends RuntypeBase<unknown>, RO extends boolean>( element: E) => Arr<E, false>;
function AsyncContract
AsyncContract: < A extends readonly RuntypeBase<unknown>[], R extends RuntypeBase<unknown>>( ...runtypes: [...A, R]) => AsyncContract<A, R>;
Create a function contract.
function Brand
Brand: <B extends string, A extends RuntypeBase<unknown>>( brand: B, entity: A) => any;
function check
check: (target: any, propertyKey: PropKey, parameterIndex: number) => void;
A parameter decorator. Explicitly mark the parameter as checked on every method call in combination with
@checked
method decorator. The number of@check
params must be the same as the number of provided runtypes into@checked
.\ Usage:@checked(Runtype1, Runtype3)method(@check p1: Static1, p2: number, @check p3: Static3) { ... }
function checked
checked: ( ...runtypes: RuntypeBase[]) => (target: any, propertyKey: PropKey, descriptor: PropertyDescriptor) => void;
A method decorator. Takes runtypes as arguments which correspond to the ones of the actual method.
Usually, the number of provided runtypes must be _**the same as**_ or _**less than**_ the actual parameters.
If you explicitly mark which parameter shall be checked using
@check
parameter decorator, the number of@check
parameters must be _**the same as**_ the runtypes provided into@checked
.Usage:
@checked(Runtype1, Runtype2)method1(param1: Static1, param2: Static2, param3: any) {...}@checked(Runtype1, Runtype3)method2(@check param1: Static1, param2: any, @check param3: Static3) {...}
function Constraint
Constraint: < A extends RuntypeBase<unknown>, T extends Static<A> = Static<A>, K = unknown>( underlying: A, constraint: ConstraintCheck<A>, options?: { name?: string; args?: K }) => Constraint<A, T, K>;
function Contract
Contract: < A extends readonly RuntypeBase<unknown>[], R extends RuntypeBase<unknown>>( ...runtypes: [...A, R]) => Contract<A, R>;
Create a function contract.
function Dictionary
Dictionary: { <V extends RuntypeBase<unknown>, K extends DictionaryKeyRuntype>( value: V, key?: K ): Dictionary<V, Static<K>>; <V extends RuntypeBase<unknown>>(value: V, key: 'string'): StringDictionary<V>; <V extends RuntypeBase<unknown>>(value: V, key: 'number'): NumberDictionary<V>;};
Construct a runtype for arbitrary dictionaries.
Parameter value
A
Runtype
for value.Parameter key
A
Runtype
for key.Construct a runtype for arbitrary dictionaries.
Parameter value
A
Runtype
for value.Parameter key
A string representing a type for key.
Deprecated
When you want to specify
key
, pass aRuntype
for it.
function Guard
Guard: <T, K = unknown>( guard: (x: unknown) => x is T, options?: { name?: string | undefined; args?: K }) => Constraint<Unknown, T, K>;
function InstanceOf
InstanceOf: <V>(ctor: Constructor<V>) => InstanceOf<V>;
function InternalRecord
InternalRecord: < O extends { [_: string]: RuntypeBase<unknown> }, Part extends boolean, RO extends boolean>( fields: O, isPartial: Part, isReadonly: RO) => InternalRecord<O, Part, RO>;
Construct a record runtype from runtypes for its values.
function Intersect
Intersect: < A extends readonly [RuntypeBase<unknown>, ...RuntypeBase<unknown>[]]>( ...intersectees: A) => Intersect<A>;
Construct an intersection runtype from runtypes for its alternatives.
function Lazy
Lazy: <A extends RuntypeBase<unknown>>(delayed: () => A) => A;
Construct a possibly-recursive Runtype.
function Literal
Literal: <A extends LiteralBase>(valueBase: A) => Literal<A>;
Construct a runtype for a type literal.
function match
match: <A extends [PairCase<any, any>, ...PairCase<any, any>[]]>( ...cases: A) => Matcher< { [key in keyof A]: A[key] extends PairCase< infer RT extends RuntypeBase<unknown>, any > ? RT : unknown; }, { [key in keyof A]: A[key] extends PairCase<any, infer Z> ? Z : unknown }[number]>;
function Optional
Optional: <R extends RuntypeBase<unknown>>(runtype: R) => Optional<R>;
Validates optional value.
function Partial
Partial: <O extends { [_: string]: RuntypeBase<unknown> }>( fields: O) => Partial<O, false>;
function Record
Record: <O extends { [_: string]: RuntypeBase<unknown> }>( fields: O) => Record<O, false>;
function Template
Template: { <A extends TemplateStringsArray, B extends readonly RuntypeBase<LiteralBase>[]>( strings: A, ...runtypes: B ): Template<A & [string, ...string[]], B>; < A extends readonly [string, ...string[]], B extends readonly RuntypeBase<LiteralBase>[] >( strings: A, ...runtypes: B ): Template<A, B>; <A extends readonly (LiteralBase | RuntypeBase<LiteralBase>)[]>( ...args: A ): Template<ExtractStrings<A, ''>, ExtractRuntypes<A>>;};
Validates that a value is a string that conforms to the template.
You can use the familiar syntax to create a
Template
runtype:const T = Template`foo${Literal('bar')}baz`;But then the type inference won't work:
type T = Static<typeof T>; // inferred as stringBecause TS doesn't provide the exact string literal type information (
["foo", "baz"]
in this case) to the underlying function. See the issue [microsoft/TypeScript#33304](https://github.com/microsoft/TypeScript/issues/33304), especially this comment [microsoft/TypeScript#33304 (comment)](https://github.com/microsoft/TypeScript/issues/33304#issuecomment-697977783) we hope to be implemented.If you want the type inference rather than the tagged syntax, you have to manually write a function call:
const T = Template(['foo', 'baz'] as const, Literal('bar'));type T = Static<typeof T>; // inferred as "foobarbaz"As a convenient solution for this, it also supports another style of passing arguments:
const T = Template('foo', Literal('bar'), 'baz');type T = Static<typeof T>; // inferred as "foobarbaz"You can pass various things to the
Template
constructor, as long as they are assignable tostring | number | bigint | boolean | null | undefined
and the correspondingRuntype
s:// Equivalent runtypesTemplate(Literal('42'));Template(42);Template(Template('42'));Template(4, '2');Template(Literal(4), '2');Template(String.withConstraint(s => s === '42'));Template(Intersect(Number.withConstraint(n => n === 42),String.withConstraint(s => s.length === 2),// `Number`s in `Template` accept alternative representations like `"0x2A"`,// thus we have to constraint the length of string, to accept only `"42"`),);Trivial items such as bare literals,
Literal
s, and single-elementUnion
s andIntersect
s are all coerced into strings at the creation time of the runtype. Additionally,Union
s of such runtypes are converted intoRegExp
patterns like(?:foo|bar|...)
, so we can assumeUnion
ofLiteral
s is a fully supported runtype inTemplate
.### Caveats
A
Template
internally constructs aRegExp
to parse strings. This can lead to a problem if it contains multiple non-literal runtypes:const UpperCaseString = Constraint(String, s => s === s.toUpperCase(), {name: 'UpperCaseString',});const LowerCaseString = Constraint(String, s => s === s.toLowerCase(), {name: 'LowerCaseString',});Template(UpperCaseString, LowerCaseString);The only thing we can do for parsing such strings correctly is brute-forcing every single possible combination until it fulfills all the constraints, which must be hardly done. Actually
Template
treatsString
runtypes as the simplestRegExp
pattern.*
and the “greedy” strategy is always used, that is, the above runtype won't work expectedly because the entire pattern is just^(.*)(.*)$
and the first.*
always wins. You have to avoid usingConstraint
this way, and instead manually parse it using a singleConstraint
which covers the entire string.
function Tuple
Tuple: <T extends readonly RuntypeBase<unknown>[]>(...components: T) => Tuple<T>;
Construct a tuple runtype from runtypes for each of its elements.
function Union
Union: <T extends readonly [RuntypeBase<unknown>, ...RuntypeBase<unknown>[]]>( ...alternatives: T) => Union<T>;
Construct a union runtype from runtypes for its alternatives.
function when
when: <A extends RuntypeBase<any>, B>( runtype: A, transformer: (value: Static<A>) => B) => PairCase<A, B>;
Classes
class ValidationError
class ValidationError extends Error {}
constructor
constructor(failure: Failure);
property code
code: Failcode;
property details
details?: Details;
property name
name: string;
Interfaces
interface Array
interface Arr<E extends RuntypeBase, RO extends boolean> extends Runtype<ArrayStaticType<E, RO>> {}
property element
element: E;
property isReadonly
isReadonly: RO;
property tag
tag: 'array';
method asReadonly
asReadonly: () => Arr<E, true>;
interface AsyncContract
interface AsyncContract<A extends readonly RuntypeBase[], R extends RuntypeBase> {}
method enforce
enforce: ( f: ( ...args: { [K in keyof A]: A[K] extends RuntypeBase<unknown> ? Static<A[K]> : unknown; } ) => Promise<Static<R>>) => ( ...args: { [K in keyof A]: A[K] extends RuntypeBase<unknown> ? Static<A[K]> : unknown; }) => Promise<Static<R>>;
interface Brand
interface Brand<B extends string, A extends RuntypeBase> extends Runtype<Static<A> & RuntypeBrand<B>> {}
interface Constraint
interface Constraint< A extends RuntypeBase, T extends Static<A> = Static<A>, K = unknown> extends Runtype<T> {}
property args
args?: K;
property name
name?: string;
property tag
tag: 'constraint';
property underlying
underlying: A;
method constraint
constraint: (x: Static<A>) => boolean | string;
interface Contract
interface Contract<A extends readonly RuntypeBase[], R extends RuntypeBase> {}
method enforce
enforce: ( f: ( ...args: { [K in keyof A]: A[K] extends RuntypeBase<unknown> ? Static<A[K]> : unknown; } ) => Static<R>) => ( ...args: { [K in keyof A]: A[K] extends RuntypeBase<unknown> ? Static<A[K]> : unknown; }) => Static<R>;
interface Dictionary
interface Dictionary<V extends RuntypeBase, K extends DictionaryKeyType> extends Runtype< V extends Optional<any> ? { [_ in K]?: Static<V>; } : { [_ in K]: Static<V>; } > {}
interface Function
interface Function extends Runtype<(...args: any[]) => any> {}
property tag
tag: 'function';
interface InstanceOf
interface InstanceOf<V> extends Runtype<V> {}
interface InternalRecord
interface InternalRecord< O extends { [_: string]: RuntypeBase; }, Part extends boolean, RO extends boolean> extends Runtype<RecordStaticType<O, Part, RO>> {}
property fields
fields: O;
property isPartial
isPartial: Part;
property isReadonly
isReadonly: RO;
property tag
tag: 'record';
method asPartial
asPartial: () => InternalRecord<O, true, RO>;
method asReadonly
asReadonly: () => InternalRecord<O, Part, true>;
method extend
extend: <P extends { [_: string]: RuntypeBase<unknown> }>(fields: { [K in keyof P]: K extends keyof O ? Static<P[K]> extends Static<O[K]> ? P[K] : RuntypeBase<Static<O[K]>> : P[K];}) => InternalRecord< { [K in keyof (O & P)]: K extends keyof P ? P[K] : K extends keyof O ? O[K] : never; }, Part, RO>;
method omit
omit: <K extends keyof O>( ...keys: K[] extends (keyof O)[] ? K[] : never[]) => InternalRecord<Omit<O, K>, Part, RO>;
method pick
pick: <K extends keyof O>( ...keys: K[] extends (keyof O)[] ? K[] : never[]) => InternalRecord<Pick<O, K>, Part, RO>;
interface Intersect
interface Intersect<A extends readonly [RuntypeBase, ...RuntypeBase[]]> extends Runtype< { [K in keyof A]: A[K] extends RuntypeBase ? (parameter: Static<A[K]>) => any : unknown; }[number] extends (k: infer I) => void ? I : never > {}
property intersectees
intersectees: A;
property tag
tag: 'intersect';
interface Literal
interface Literal<A extends LiteralBase> extends Runtype<A> {}
interface Match
interface Match<A extends readonly [RuntypeBase, ...RuntypeBase[]]> {}
call signature
<Z>( ...a: { [K in keyof A]: A[K] extends RuntypeBase ? Case<A[K], Z> : never; }): Matcher<A, Z>;
interface NumberDictionary
interface NumberDictionary<V extends RuntypeBase> extends Runtype< V extends Optional<any> ? { [_ in number]?: Static<V>; } : { [_ in number]: Static<V>; } > {}
interface Optional
interface Optional<R extends RuntypeBase> extends Runtype<Static<R> | undefined> {}
property tag
tag: 'optional';
property underlying
underlying: R;
interface Runtype
interface Runtype<A = unknown> extends RuntypeBase<A> {}
A runtype determines at runtime whether a value conforms to a type specification.
method And
And: <B extends RuntypeBase<unknown>>(B: B) => Intersect<[this, B]>;
Intersect this Runtype with another.
method nullable
nullable: () => Union<[this, typeof Null]>;
Union this Runtype with
Null
.
method optional
optional: () => Optional<this>;
Optionalize this Runtype.
method Or
Or: <B extends RuntypeBase<unknown>>(B: B) => Union<[this, B]>;
Union this Runtype with another.
method withBrand
withBrand: <B extends string>(brand: B) => Brand<B, this>;
Adds a brand to the type.
method withConstraint
withConstraint: <T extends Static<this>, K = unknown>( constraint: ConstraintCheck<this>, options?: { name?: string; args?: K }) => Constraint<this, T, K>;
Use an arbitrary constraint function to validate a runtype, and optionally to change its name and/or its static type.
T - Optionally override the static type of the resulting runtype
Parameter constraint
Custom function that returns
true
if the constraint is satisfied,false
or a custom error message if not.Parameter options
Parameter
{string} [options.name] - allows setting the name of this constrained runtype, which is helpful in reflection or diagnostic use-cases.
method withGuard
withGuard: <T extends Static<this>, K = unknown>( guard: (x: Static<this>) => x is T, options?: { name?: string; args?: K }) => Constraint<this, T, K>;
Helper function to convert an underlying Runtype into another static type via a type guard function. The static type of the runtype is inferred from the type of the guard function.
T - Typically inferred from the return type of the type guard function, so usually not needed to specify manually.
Parameter guard
Type guard function (see https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards)
Parameter options
Parameter
{string} [options.name] - allows setting the name of this constrained runtype, which is helpful in reflection or diagnostic use-cases.
interface RuntypeBrand
interface RuntypeBrand<B extends string> {}
property [RuntypeName]
[RuntypeName]: { [k in B]: B;};
interface StringDictionary
interface StringDictionary<V extends RuntypeBase> extends Runtype< V extends Optional<any> ? { [_ in string]?: Static<V>; } : { [_ in string]: Static<V>; } > {}
interface Symbol
interface Symbol extends Runtype<symbol> {}
property tag
tag: 'symbol';
call signature
<K extends string | undefined>(key: K): SymbolFor<K>;
Validates that a value is a symbol with a specific key or without any key.
Parameter key
Specify what key the symbol is for. If you want to ensure the validated symbol is *not* keyed, pass
undefined
.
interface SymbolFor
interface SymbolFor<K extends string | undefined> extends Runtype<symbol> {}
interface Template
interface Template< A extends readonly [string, ...string[]], B extends readonly RuntypeBase<LiteralBase>[]> extends Runtype< A extends TemplateStringsArray ? string : TemplateLiteralType<A, B> > {}
interface Tuple
interface Tuple<A extends readonly RuntypeBase[]> extends Runtype<{ [K in keyof A]: A[K] extends RuntypeBase ? Static<A[K]> : unknown; }> {}
property components
components: A;
property tag
tag: 'tuple';
interface Union
interface Union<A extends readonly [RuntypeBase, ...RuntypeBase[]]> extends Runtype< { [K in keyof A]: A[K] extends RuntypeBase ? Static<A[K]> : unknown; }[number] > {}
Type Aliases
type Case
type Case<T extends RuntypeBase, Result> = (v: Static<T>) => Result;
type ConstraintCheck
type ConstraintCheck<A extends RuntypeBase> = (x: Static<A>) => boolean | string;
type Details
type Details = | (string | Details)[] | { [key in string | number | symbol]: string | Details; };
A detailed object enumerating where the validation failed exactly.
type Failcode
type Failcode = typeof Failcode[keyof typeof Failcode];
A predefined error code indicating what type of failure has occured.
type Failure
type Failure = { /** * A tag indicating failure. */ success: false; /** * An error code assigned to this type of error. */ code: Failcode; /** * A message indicating the reason why the validation failed. */ message: string; /** * A detailed object enumerating where the validation failed exactly. */ details?: Details;};
A failed validation result.
type Matcher
type Matcher<A extends readonly [RuntypeBase, ...RuntypeBase[]], Z> = ( x: { [K in keyof A]: A[K] extends RuntypeBase<infer Type> ? Type : unknown; }[number]) => Z;
type PairCase
type PairCase<A extends RuntypeBase, Z> = [A, Case<A, Z>];
type Partial
type Partial< O extends { [_: string]: RuntypeBase; }, RO extends boolean> = InternalRecord<O, true, RO>;
type Record
type Record< O extends { [_: string]: RuntypeBase; }, RO extends boolean> = InternalRecord<O, false, RO>;
type Reflect
type Reflect = | ({ tag: 'unknown'; } & Runtype) | ({ tag: 'never'; } & Runtype<never>) | ({ tag: 'void'; } & Runtype<void>) | ({ tag: 'boolean'; } & Runtype<boolean>) | ({ tag: 'number'; } & Runtype<number>) | ({ tag: 'bigint'; } & Runtype<bigint>) | ({ tag: 'string'; } & Runtype<string>) | ({ tag: 'symbol'; key: string | undefined; } & Runtype<symbol>) | ({ tag: 'symbol'; (key: string | undefined): Runtype<symbol>; } & Runtype<symbol>) | ({ tag: 'literal'; value: LiteralBase; } & Runtype<LiteralBase>) | ({ tag: 'template'; strings: string[]; runtypes: Runtype<LiteralBase>[]; } & Runtype<string>) | ({ tag: 'array'; element: Reflect; isReadonly: boolean; } & Runtype<ReadonlyArray<unknown>>) | ({ tag: 'record'; fields: { [_: string]: Reflect; }; isPartial: boolean; isReadonly: boolean; } & Runtype<{ readonly [_ in string]: unknown; }>) | ({ tag: 'dictionary'; key: 'string' | 'number' | 'symbol'; value: Reflect; } & Runtype<{ [_: string]: unknown; }>) | ({ tag: 'tuple'; components: Reflect[]; } & Runtype<unknown[]>) | ({ tag: 'union'; alternatives: Reflect[]; } & Runtype) | ({ tag: 'intersect'; intersectees: Reflect[]; } & Runtype) | ({ tag: 'optional'; underlying: Reflect; } & Runtype) | ({ tag: 'function'; } & Runtype<(...args: any[]) => any>) | ({ tag: 'constraint'; underlying: Reflect; constraint: ConstraintCheck<Runtype<never>>; args?: any; name?: string; } & Runtype) | ({ tag: 'instanceof'; ctor: Constructor<unknown>; } & Runtype) | ({ tag: 'brand'; brand: string; entity: Reflect; } & Runtype);
type Result
type Result<T> = Success<T> | Failure;
The result of a type validation.
type Static
type Static<A extends RuntypeBase> = A['_falseWitness'];
Obtains the static type associated with a Runtype.
type Success
type Success<T> = { /** * A tag indicating success. */ success: true; /** * The original value, cast to its validated type. */ value: T;};
A successful validation result.
type Void
type Void = Unknown;
Package Files (31)
- lib/asynccontract.d.ts
- lib/contract.d.ts
- lib/decorator.d.ts
- lib/errors.d.ts
- lib/index.d.ts
- lib/match.d.ts
- lib/reflect.d.ts
- lib/result.d.ts
- lib/runtype.d.ts
- lib/types/array.d.ts
- lib/types/bigint.d.ts
- lib/types/boolean.d.ts
- lib/types/brand.d.ts
- lib/types/constraint.d.ts
- lib/types/dictionary.d.ts
- lib/types/function.d.ts
- lib/types/instanceof.d.ts
- lib/types/intersect.d.ts
- lib/types/lazy.d.ts
- lib/types/literal.d.ts
- lib/types/never.d.ts
- lib/types/number.d.ts
- lib/types/optional.d.ts
- lib/types/record.d.ts
- lib/types/string.d.ts
- lib/types/symbol.d.ts
- lib/types/template.d.ts
- lib/types/tuple.d.ts
- lib/types/union.d.ts
- lib/types/unknown.d.ts
- lib/types/void.d.ts
Dependencies (0)
No dependencies.
Dev Dependencies (8)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/runtypes
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/runtypes)
- HTML<a href="https://www.jsdocs.io/package/runtypes"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5716 ms. - Missing or incorrect documentation? Open an issue for this package.