runtypes
- Version 7.0.4
- Published
- 312 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
Namespaces
Variables
variable BigInt
const BigInt: BigInt;
variable Boolean
const Boolean: 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 ARGUMENTS_INCORRECT: 'ARGUMENTS_INCORRECT'; readonly RETURN_INCORRECT: 'RETURN_INCORRECT'; readonly RESOLVE_INCORRECT: 'RESOLVE_INCORRECT'; readonly CONSTRAINT_FAILED: 'CONSTRAINT_FAILED'; readonly PROPERTY_MISSING: 'PROPERTY_MISSING'; readonly PROPERTY_PRESENT: 'PROPERTY_PRESENT'; readonly NOTHING_EXPECTED: 'NOTHING_EXPECTED'; readonly PARSING_FAILED: 'PARSING_FAILED'; readonly INSTANCEOF_FAILED: 'INSTANCEOF_FAILED';};
variable Function
const Function: Function;
variable Never
const Never: Never;
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;
variable Optional
const Optional: { <R extends Runtype.Core<any, any>>(underlying: R): Optional<R, never>; <R extends Runtype.Core<any, any>, D>(underlying: R, defaultValue: D): Optional< R, D >; isOptional: ( runtype: Runtype.Core | Optional ) => runtype is Optional<Runtype.Core<any, any>, any>;};
variable Spread
const Spread: { <R extends Runtype.Spreadable>( content: HasSymbolIterator<R> extends true ? R : never ): Spread<R>; asSpreadable: <B extends Runtype.Base<any>>(base: B) => B;};
variable String
const String: string;
variable Symbol
const Symbol: Symbol<never>;
variable Template
const Template: { < A extends TemplateStringsArray, B extends readonly Runtype.Core<LiteralStatic, LiteralStatic>[] >( strings: A, ...runtypes: B ): Template<A & [string, ...string[]], B>; < A extends readonly [string, ...string[]], B extends readonly Runtype.Core<LiteralStatic, LiteralStatic>[] >( strings: A, ...runtypes: B ): Template<A, B>; < A extends readonly ( | LiteralStatic | Runtype.Core<LiteralStatic, LiteralStatic> )[] >( ...args: A ): Template<ExtractStrings<A, ''>, ExtractRuntypes<A>>;};
variable Undefined
const Undefined: Literal<undefined>;
An alias for
Literal(undefined)
.
variable Unknown
const Unknown: Unknown;
variable Void
const Void: Unknown;
An alias for
Unknown
.Deprecated
Use
Unknown
instead.
variable when
const when: { <R extends Runtype.Core<any, any>, Y>( runtype: R, transformer: (value: Parsed<R>) => Y ): Case<R, Y>; <R extends Runtype.Core<any, any>, Y>(case_: CaseArgs<R, Y>): Case<R, Y>;};
Functions
function Array
Array: <R extends Runtype.Core<any, any>>(element: R) => Array<R>;
function AsyncContract
AsyncContract: <O extends Options>({ receives, resolves,}: O) => AsyncContract<O>;
Creates an async function contract.
Possible failures:
-
ARGUMENTS_INCORRECT
withdetail
reporting the inner failures -RETURN_INCORRECT
withdetail
reporting that the returned value is not aPromise
-RESOLVE_INCORRECT
withdetail
reporting the inner failure
function Brand
Brand: <B extends string, R extends Runtype.Core<any, any>>( brand: B, entity: R) => Brand<B, R>;
function Constraint
Constraint: <R extends Runtype.Core<any, any>, T extends Parsed<R>>( underlying: R, constraint: (x: Parsed<R>) => asserts x is T) => Constraint<R, T>;
function Contract
Contract: <O extends Options>({ receives, returns }: O) => Contract<O>;
Creates an function contract.
Possible failures:
-
ARGUMENTS_INCORRECT
withdetail
reporting the inner failures -RETURN_INCORRECT
withdetail
reporting the inner failure
function InstanceOf
InstanceOf: <V>(ctor: Constructor<V>) => InstanceOf<V>;
function Intersect
Intersect: <R extends readonly Runtype.Core<any, any>[]>( ...intersectees: R) => Intersect<R>;
function Lazy
Lazy: <R extends Runtype.Core<any, any>>(delayed: () => R) => R;
Constructs a possibly-recursive runtype.
function Literal
Literal: <T extends LiteralStatic>(value: T) => Literal<T>;
function match
match: <C extends readonly [Case<any, any>, ...Case<any, any>[]]>( ...cases: C) => Matcher< { [K in keyof C]: C[K] extends Case< infer R extends Runtype.Core<any, any>, any > ? R : unknown; }, { [K in keyof C]: C[K] extends Case<any, infer Y> ? Y : unknown }[number]>;
function Object
Object: <O extends Object.Fields>(fields: O) => Object<O>;
function Parser
Parser: <R extends Runtype.Core<any, any>, X>( underlying: R, parser: (value: Parsed<R>) => X) => Parser<R, X>;
function Record
Record: < K extends Runtype.Core<PropertyKey, PropertyKey>, V extends Runtype.Core<any, any>>( key: K, value: V) => Record<K, V>;
function Tuple
Tuple: < R extends readonly (Runtype.Core<any, any> | Spread<Runtype.Spreadable>)[]>( ...components: R) => Tuple<R>;
function Union
Union: <R extends readonly Runtype.Core<any, any>[]>( ...alternatives: R) => Union<R>;
Classes
class Runtype
class Runtype<T = any, X = T> implements Conformance<T, X> {}
A runtype determines at runtime whether a value conforms to a type specification.
property [globalThis.Symbol.hasInstance]
static [globalThis.Symbol.hasInstance]: (x: unknown) => x is Runtype.Interfaces;
property [globalThis.Symbol.toStringTag]
readonly [globalThis.Symbol.toStringTag]: globalThis.String;
property assertIsRuntype
static assertIsRuntype: (x: unknown) => asserts x is Runtype.Interfaces;
Asserts if a value is a runtype.
property isRuntype
static isRuntype: (x: unknown) => x is Runtype.Interfaces;
Guards if a value is a runtype.
property tag
tag: globalThis.String;
method and
and: <R extends Runtype.Core<any, any>>(other: R) => Intersect<[this, R]>;
Intersects this Runtype with another.
method assert
assert: <U = T>(x: Target<T, U, this>) => asserts x is Validated<T, U>;
Validates that a value conforms to this runtype. Throws
ValidationError
on failure.
method check
check: <U = T>(x: Target<T, U, this>) => Validated<T, U>;
Validates that a value conforms to this runtype, returning the original value, statically typed. Throws
ValidationError
on failure.
method clone
clone: () => this;
Creates a shallow clone of this runtype.
method conform
conform: <T, X = T>(this: Conform<T, X>) => Conform<T, X> & this;
Statically ensures this runtype is defined for exactly
T
, not for a subtype ofT
.X
is for the parsed type.
method default
default: <X = never>(value: X) => Optional<this, X>;
Optionalizes this property, defaulting to the given value if this property was absent. Only meaningful for parsing.
method guard
guard: <U = T>(x: Target<T, U, this>) => x is Validated<T, U>;
Validates that a value conforms to this runtype, returning a
boolean
that represents success or failure. Does not throw on failure.
method inspect
inspect: <U, P extends boolean = true>( x: U, options?: { parse?: P | undefined }) => Result<P extends true ? X : Validated<T, U>>;
Process a value with this runtype, returning a detailed information of success or failure. Does not throw on failure.
method nullable
nullable: () => Union<[this, Literal<null>]>;
Unions this runtype with
Null
.
method nullishable
nullishable: () => Union<[this, Literal<null>, Literal<undefined>]>;
Unions this runtype with
Null
andUndefined
.
method optional
optional: () => Optional<this, never>;
Optionalizes this property.
Note that
Optional
is not a runtype, but just a contextual modifier which is only meaningful when defining the content ofObject
. If you want to allow the validated value to beundefined
, useundefinedable
method.
method or
or: <R extends Runtype.Core<any, any>>(other: R) => Union<[this, R]>;
Unions this Runtype with another.
method parse
parse: <U = T>(x: Target<T, U, this>) => X;
Validates that a value conforms to this runtype and returns another value returned by the function passed to
withParser
. ThrowsValidationError
on failure. Does not modify the original value.
method toString
toString: () => string;
method undefinedable
undefinedable: () => Union<[this, Literal<undefined>]>;
Unions this runtype with
Undefined
.
method with
with: <P extends object>(extension: P | ((self: this) => P)) => this & P;
Returns a shallow clone of this runtype with additional properties. Useful when you want to integrate related values, such as the default value and utility functions.
method withAssertion
withAssertion: <Y extends X>( assert: (x: X) => asserts x is Y) => Constraint<this, Y>;
Uses an assertion function to add additional constraints to this runtype, and automatically converts a static type of this runtype into another.
method withBrand
withBrand: <B extends string>(brand: B) => Brand<B, this>;
Adds a brand to the type.
method withConstraint
withConstraint: <Y extends X>( constraint: (x: X) => boolean | string) => Constraint<this, Y>;
Uses a constraint function to add additional constraints to this runtype, and manually converts a static type of this runtype into another via the type argument if passed.
method withGuard
withGuard: <Y extends X>(guard: (x: X) => x is Y) => Constraint<this, Y>;
Uses a guard function to add additional constraints to this runtype, and automatically converts a static type of this runtype into another.
method withParser
withParser: <Y>(parser: (value: X) => Y) => Parser<this, Y>;
Chains custom parser after this runtype. Basically only works in the
parse
method, but in certain cases parsing is implied within a chain of normal validation, such as before execution of a constraint, or upon function boundaries enforced withContract
andAsyncContract
.
class ValidationError
class ValidationError extends Error {}
constructor
constructor(failure: Failure);
property [globalThis.Symbol.hasInstance]
static [globalThis.Symbol.hasInstance]: ( value: unknown) => value is ValidationError;
property failure
failure: Failure;
An object that describes the problem in a structured way.
property isValidationError
static isValidationError: (value: unknown) => value is ValidationError;
property message
message: string;
A string that summarizes the problem overall.
property name
name: string;
Always
"ValidationError"
.
Interfaces
interface Array
interface Array<R extends Runtype.Core = Runtype.Core> extends Runtype<Static<R>[], Parsed<R>[]>, Iterable<Spread<Array<R>>> {}
Validates a value is an array of the given element type.
Possible failures:
-
TYPE_INCORRECT
for non-arrays -CONTENT_INCORRECT
withdetails
reporting the failed elements
property asReadonly
asReadonly: () => Array.Readonly<R>;
property element
element: R;
property tag
tag: 'array';
interface BigInt
interface BigInt extends Runtype<bigint> {}
Validates that a value is a bigint.
Possible failures:
-
TYPE_INCORRECT
for non-bigints
property tag
tag: 'bigint';
interface Boolean
interface Boolean extends Runtype<boolean> {}
Validates that a value is a boolean.
Possible failures:
-
TYPE_INCORRECT
for non-booleans
property tag
tag: 'boolean';
interface Brand
interface Brand<B extends string = string, R extends Runtype.Core = Runtype.Core> extends Runtype<Static<R> & RuntypeBrand<B>, Parsed<R> & RuntypeBrand<B>> {}
Adds a brand to the inferred static type.
Possible failures:
-
TYPE_INCORRECT
withdetail
reporting the inner failure
property [Symbol.iterator]
[Symbol.iterator]: R extends Runtype.Spreadable ? HasSymbolIterator<R> extends true ? () => Iterator<Spread<Brand<B, R>>> : never : never;
property brand
brand: B;
property entity
entity: R;
property tag
tag: 'brand';
interface Constraint
interface Constraint< R extends Runtype.Core = Runtype.Core, T extends Parsed<R> = Parsed<R>> extends Runtype< [Static<R>, Parsed<R>] extends [Parsed<R>, Static<R>] ? T : Static<R>, T > {}
Adds a constraint to a runtype, narrowing its inferred static type.
Possible failures:
- Failures of the inner runtype -
CONSTRAINT_FAILED
withthrown
reporting the thrown value from the constraint function
property constraint
constraint: (x: Parsed<R>) => asserts x is T;
property tag
tag: 'constraint';
property underlying
underlying: R;
interface Function
interface Function extends Runtype<(...args: never[]) => unknown> {}
Validates that a value is a function.
Possible failures:
-
TYPE_INCORRECT
for non-functions
property tag
tag: 'function';
interface InstanceOf
interface InstanceOf<V = unknown> extends Runtype<V> {}
Validates that a value is an instance of the given class.
Possible failures:
-
TYPE_INCORRECT
ifinstanceof
wasfalse
-INSTANCEOF_FAILED
ifinstanceof
threw (perSymbol.hasInstance
)
interface Intersect
interface Intersect<R extends readonly Runtype.Core[] = readonly Runtype.Core[]> extends Runtype< { [K in keyof R]: (_: Static<R[K]>) => unknown; }[number] extends (_: infer I) => unknown ? I : unknown, R extends [...(readonly unknown[]), infer R] ? R extends Runtype.Core ? Parsed<R> : never : unknown > {}
Validates that a value fulfills all of the given runtypes.
Possible failures:
-
TYPE_INCORRECT
withdetails
reporting failures for each runtype
property [Symbol.iterator]
[Symbol.iterator]: R['length'] extends 1 ? R[0] extends Runtype.Spreadable ? HasSymbolIterator<R[0]> extends true ? () => Iterator<Spread<R[0]>> : never : never : never;
property intersectees
intersectees: R;
property tag
tag: 'intersect';
interface Literal
interface Literal<T extends LiteralStatic = LiteralStatic> extends Runtype<T> {}
Validates that a value is equal to the given value with the [
SameValueZero
](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality) equality.Possible failures:
-
TYPE_INCORRECT
if they have differenttypeof
s -VALUE_INCORRECT
if they were different as perSameValueZero
interface Never
interface Never extends Runtype<never> {}
Validates nothing.
Possible failures:
-
NOTHING_EXPECTED
for any value
property tag
tag: 'never';
interface Number
interface Number extends Runtype<number> {}
Validates that a value is a number.
Possible failures:
-
TYPE_INCORRECT
for non-numbers
property tag
tag: 'number';
interface Object
interface Object<O extends Object.Fields = Object.Fields> extends Runtype<ObjectStatic<O>, ObjectParsed<O>>, Utilities<O> {}
Validates that a value is an object and each property fulfills the given property runtype.
Possible failures:
-
TYPE_INCORRECT
fornull
,undefined
, and non-objects if fields were non-empty -CONTENT_INCORRECT
withdetails
reporting the failed propertiesFor each property, contextual failures can be seen in addition to failures of the property runtype:
-
PROPERTY_MISSING
for missing required properties -PROPERTY_PRESENT
for extraneous properties where.exact()
flag is enabled
interface Optional
interface Optional<R extends Runtype.Core = Runtype.Core, D = any> {}
A pseudo-runtype that is only usable in the context of
Object
properties. This works as the runtime counterpart of optional properties.const O = Object({ x: Number.optional() })const O = Static<typeof O> // { x?: number }
interface Parser
interface Parser<R extends Runtype.Core = Runtype.Core, X = Parsed<R>> extends Runtype<Static<R>, X> {}
Adds a parser to the given runtype.
Possible failures when
check
-ing:- Failures of the inner runtype
Possible failures when
parse
-ing:- Failures of the inner runtype -
PARSING_FAILED
withthrown
reporting the thrown value from the parser function
property parser
parser: (value: Parsed<R>) => X;
property tag
tag: 'parser';
property underlying
underlying: R;
interface Record
interface Record< K extends Runtype.Core<PropertyKey> = Runtype.Core<PropertyKey>, V extends Runtype.Core = Runtype.Core> extends Runtype<RecordStatic<K, V>, RecordParsed<K, V>> {}
Validates that a value is an object, and properties fulfill the given key and value runtypes.
Possible failures:
-
TYPE_INCORRECT
fornull
,undefined
, non-objects, non-plain-object non-arrays, and non-plain-object arrays if the key runtype wasString
-CONTENT_INCORRECT
withdetails
reporting the failed propertiesFor each property, contextual failures can be seen in addition to failures of the property runtype:
-
PROPERTY_MISSING
for missing required properties -KEY_INCORRECT
withdetail
reporting the failure of the key runtype
interface Spread
interface Spread<R extends Runtype.Spreadable = Runtype.Spreadable> {}
A pseudo-runtype that is only usable in the context of
Tuple
arguments. This works as the runtime counterpart of variadic tuple types.const T = Tuple(Literal(0), Spread(Tuple(Literal(1), Literal(2))), Literal(3))type T = Static<typeof T> // [0, 1, 2, 3]const U = Tuple(Literal(0), Spread(Array(Literal(1))), Literal(2))type U = Static<typeof U> // [0, ...1[], 2]Spread
only accepts aTuple
, anArray
, and trivial runtypes around them e.g.Tuple(...).withBrand(...)
andUnion(Array(...))
. Using the spread operator...
against those runtypes yields aSpread
just once, so you can write...Tuple(...)
instead ofSpread(Tuple(...))
.const T = Tuple(Literal(0), ...Tuple(Literal(1), Literal(2)), Literal(3))type T = Static<typeof T> // [0, 1, 2, 3]const U = Tuple(Literal(0), ...Array(Literal(1)), Literal(2))type U = Static<typeof U> // [0, ...1[], 2]
interface String
interface String extends Runtype<string> {}
Validates that a value is a string.
Possible failures:
-
TYPE_INCORRECT
for non-strings
property tag
tag: 'string';
interface Symbol
interface Symbol<K extends string | undefined = never> extends Runtype<symbol> {}
Validates that a value is a symbol, and optionally the key is equal to the given one. If you want to ensure a symbol is *not* keyed, pass
undefined
.Possible failures:
-
TYPE_INCORRECT
for non-symbols -VALUE_INCORRECT
if the key is not equal to the given one
property key
key?: K;
property tag
tag: 'symbol';
call signature
<K extends string | undefined>(key: K): Symbol<K>;
interface Template
interface Template< A extends readonly [string, ...string[]] = readonly [string, ...string[]], B extends readonly Runtype.Core<LiteralStatic>[] = readonly Runtype.Core<LiteralStatic>[]> extends Runtype< A extends TemplateStringsArray ? string : TemplateStatic<A, B>, A extends TemplateStringsArray ? string : TemplateParsed<A, B> > {}
Validates that a value is a string that conforms to the template.
Possible failures:
-
TYPE_INCORRECT
for non-strings -VALUE_INCORRECT
if the string didn't match the templateYou 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.
interface Tuple
interface Tuple< R extends readonly (Runtype.Core | Spread)[] = readonly (Runtype.Core | Spread)[]> extends Runtype<TupleStatic<R>, TupleParsed<R>>, Iterable<Spread<Tuple<R>>> {}
Validates that a value is an array of the given element types.
Possible failures:
-
TYPE_INCORRECT
for non-arrays -CONSTRAINT_FAILED
withthrown
being a string reporting that the length constraint was not fulfilled -CONTENT_INCORRECT
withdetails
reporting the failed elements
property asReadonly
asReadonly: () => Tuple.Readonly<R>;
property components
readonly components: Tuple.Components<R> extends infer X ? { [K in keyof X]: X[K]; } : never;
property tag
tag: 'tuple';
interface Union
interface Union<R extends readonly Runtype.Core[] = readonly Runtype.Core[]> extends Runtype< { [K in keyof R]: R[K] extends Runtype.Core ? Static<R[K]> : unknown; }[number], { [K in keyof R]: R[K] extends Runtype.Core ? Parsed<R[K]> : unknown; }[number] > {}
Validates that a value fulfills one of the given runtypes.
Possible failures:
-
TYPE_INCORRECT
withdetails
reporting failures for each runtype
property [Symbol.iterator]
[Symbol.iterator]: R['length'] extends 1 ? R[0] extends Runtype.Spreadable ? HasSymbolIterator<R[0]> extends true ? () => Iterator<Spread<R[0]>> : never : never : never;
property alternatives
alternatives: R;
property match
match: Match<R>;
property tag
tag: 'union';
Type Aliases
type AsyncContract
type AsyncContract<O extends Options> = O & { enforce: < F extends ( ...args: EnforcedParametersParsed<O, F> ) => Promise<EnforcedReturnTypeStatic<O, F>> >( f: F ) => ( ...args: EnforcedParametersStatic<O, F> ) => Promise<EnforcedReturnTypeParsed<O, F>>;};
type Contract
type Contract<O extends Options> = O & { enforce: < F extends ( ...args: EnforcedParametersParsed<O, F> ) => EnforcedReturnTypeStatic<O, F> >( f: F ) => (...args: EnforcedParametersStatic<O, F>) => EnforcedReturnTypeParsed<O, F>;};
type Failcode
type Failcode = keyof typeof Failcode;
A predefined error code indicating what type of failure has occured.
type Failure
type Failure = | ((Pick<Legend, 'success' | 'message' | 'code' | 'expected' | 'received'> & (Pick<Legend, 'details'> | Pick<Legend, 'detail'> | object)) & { code: typeof Failcode.TYPE_INCORRECT; } extends infer T ? { [K in keyof T]: T[K]; } : never) | (Pick<Legend, 'success' | 'message' | 'code' | 'expected' | 'received'> & { code: typeof Failcode.VALUE_INCORRECT; } extends infer T ? { [K in keyof T]: T[K]; } : never) | (Pick<Legend, 'success' | 'message' | 'code' | 'expected' | 'received'> & Pick<Legend, 'detail'> & { code: typeof Failcode.KEY_INCORRECT; } extends infer T ? { [K in keyof T]: T[K]; } : never) | (Pick< Legend, 'success' | 'message' | 'code' | 'expected' | 'received' | 'details' > & { code: typeof Failcode.CONTENT_INCORRECT; } extends infer T ? { [K in keyof T]: T[K]; } : never) | (Pick< Legend, 'success' | 'message' | 'code' | 'expected' | 'received' | 'detail' > & { code: typeof Failcode.ARGUMENTS_INCORRECT; } extends infer T ? { [K in keyof T]: T[K]; } : never) | (Pick< Legend, 'success' | 'message' | 'code' | 'expected' | 'received' | 'detail' > & { code: typeof Failcode.RETURN_INCORRECT; } extends infer T ? { [K in keyof T]: T[K]; } : never) | (Pick< Legend, 'success' | 'message' | 'code' | 'expected' | 'received' | 'detail' > & { code: typeof Failcode.RESOLVE_INCORRECT; } extends infer T ? { [K in keyof T]: T[K]; } : never) | (Pick< Legend, 'success' | 'message' | 'code' | 'expected' | 'received' | 'thrown' > & { code: typeof Failcode.CONSTRAINT_FAILED; } extends infer T ? { [K in keyof T]: T[K]; } : never) | (Pick<Legend, 'success' | 'message' | 'code' | 'expected'> & { code: typeof Failcode.PROPERTY_MISSING; } extends infer T ? { [K in keyof T]: T[K]; } : never) | (Pick<Legend, 'success' | 'message' | 'code' | 'expected' | 'received'> & { code: typeof Failcode.PROPERTY_PRESENT; } extends infer T ? { [K in keyof T]: T[K]; } : never) | (Pick<Legend, 'success' | 'message' | 'code' | 'expected' | 'received'> & { code: typeof Failcode.NOTHING_EXPECTED; } extends infer T ? { [K in keyof T]: T[K]; } : never) | (Pick< Legend, 'success' | 'message' | 'code' | 'expected' | 'received' | 'thrown' > & { code: typeof Failcode.PARSING_FAILED; } extends infer T ? { [K in keyof T]: T[K]; } : never) | (Pick< Legend, 'success' | 'message' | 'code' | 'expected' | 'received' | 'thrown' > & { code: typeof Failcode.INSTANCEOF_FAILED; } extends infer T ? { [K in keyof T]: T[K]; } : never);
A failed validation result.
type Parsed
type Parsed< R extends { readonly [RuntypeSymbol]: [unknown, unknown]; }> = R[typeof RuntypeSymbol][1];
Obtains the parsed type associated with a runtype.
type Result
type Result<T> = Success<T> | Failure;
The result of a type validation.
type Static
type Static< R extends { readonly [RuntypeSymbol]: [unknown, unknown]; }> = R[typeof RuntypeSymbol][0];
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;
Namespaces
namespace Array
namespace Array {}
namespace Failure
namespace Failure {}
type Details
type Details = globalThis.Record<PropertyKey, Failure>;
A detailed object enumerating where the validation failed exactly.
namespace Object
namespace Object {}
namespace Runtype
namespace Runtype {}
type Core
type Core<T = any, X = T> = Pick< Runtype<T, X>, typeof RuntypeSymbol | 'tag' | 'inspect' | 'check' | 'guard' | 'assert' | 'parse'>;
An upper bound of a `Runtype`, with the bare minimum set of APIs to perform validation and parsing. Useful when you want a variable to accept any runtype; if you want to introspect the contents of it, use `Runtype.isRuntype` or `Runtype.assertIsRuntype` first and
switch
with the `Runtype.prototype.tag`.
type Interfaces
type Interfaces = | Array | Array.Readonly | BigInt | Boolean | Brand | Constraint | Function | InstanceOf | Intersect | Literal | Never | Number | Object | Object.Readonly | Parser | Record | String | Symbol | Symbol<string | undefined> | Template | Tuple | Tuple.Readonly | Union | Unknown;
The union of all possible runtypes. `Runtype.isRuntype` or `Runtype.assertIsRuntype` can be used to ensure a value is of this type.
type Spreadable
type Spreadable = Runtype.Core<readonly unknown[]> & Iterable<Spread<Spreadable>>;
namespace Tuple
namespace Tuple {}
interface Readonly
interface Readonly< R extends readonly (Runtype.Core | Spread)[] = readonly (Runtype.Core | Spread)[]> extends Runtype<ToReadonly<TupleStatic<R>>, ToReadonly<TupleParsed<R>>>, Iterable<Spread<Readonly<R>>> {}
property components
readonly components: Tuple.Components<R> extends infer X ? { [K in keyof X]: X[K]; } : never;
property tag
tag: 'tuple';
type Components
type Components<R extends readonly (Runtype.Core | Spread)[]> = FlattenSplitAtSpread<R> extends infer X ? X extends Lrt<infer L, infer R, infer T> ? unknown extends R ? [...L, ...T] : X : never : never;
namespace Tuple.Components
namespace Tuple.Components {}
type Fixed
type Fixed<R extends readonly (Runtype.Core | Spread)[] = never> = [R] extends [ never] ? readonly Runtype[] : Components<R>;
type Variadic
type Variadic<R extends readonly (Runtype.Core | Spread)[] = never> = [R] extends [ never] ? Lrt<readonly Runtype[], Runtype.Spreadable, readonly Runtype[]> : Components<R>;
Package Files (37)
- script/Array.d.ts
- script/BigInt.d.ts
- script/Boolean.d.ts
- script/Brand.d.ts
- script/Constraint.d.ts
- script/Function.d.ts
- script/InstanceOf.d.ts
- script/Intersect.d.ts
- script/Lazy.d.ts
- script/Literal.d.ts
- script/Never.d.ts
- script/Null.d.ts
- script/Nullish.d.ts
- script/Number.d.ts
- script/Object.d.ts
- script/Optional.d.ts
- script/Parser.d.ts
- script/Record.d.ts
- script/Runtype.d.ts
- script/Spread.d.ts
- script/String.d.ts
- script/Symbol.d.ts
- script/Template.d.ts
- script/Tuple.d.ts
- script/Undefined.d.ts
- script/Union.d.ts
- script/Unknown.d.ts
- script/Void.d.ts
- script/index.d.ts
- script/result/Failcode.d.ts
- script/result/Failure.d.ts
- script/result/Result.d.ts
- script/result/Success.d.ts
- script/result/ValidationError.d.ts
- script/utils/AsyncContract.d.ts
- script/utils/Contract.d.ts
- script/utils/match.d.ts
Dependencies (0)
No dependencies.
Dev Dependencies (0)
No dev dependencies.
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[](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 4430 ms. - Missing or incorrect documentation? Open an issue for this package.