superstruct
- Version 2.0.2
- Published
- 182 kB
- No dependencies
- MIT license
Install
npm i superstruct
yarn add superstruct
pnpm add superstruct
Overview
A simple and composable way to validate data in JavaScript (and TypeScript).
Index
Functions
- any()
- array()
- assert()
- assign()
- bigint()
- boolean()
- coerce()
- create()
- date()
- defaulted()
- define()
- deprecated()
- dynamic()
- empty()
- enums()
- func()
- instance()
- integer()
- intersection()
- is()
- lazy()
- literal()
- map()
- mask()
- max()
- min()
- never()
- nonempty()
- nullable()
- number()
- object()
- omit()
- optional()
- partial()
- pattern()
- pick()
- record()
- refine()
- regexp()
- set()
- size()
- string()
- struct()
- trimmed()
- tuple()
- type()
- union()
- unknown()
- validate()
Classes
Type Aliases
Functions
function any
any: () => Struct<any, null>;
Ensure that any value passes validation.
function array
array: { <T extends Struct<any, unknown>>(Element: T): Struct<Infer<T>[], T>; (): Struct<unknown[], undefined>;};
Ensure that a value is an array and that its elements are of a specific type.
Note: If you omit the element struct, the arrays elements will not be iterated at all. This can be helpful for cases where performance is critical, and it is preferred to using
array(any())
.
function assert
assert: <T, S>( value: unknown, struct: Struct<T, S>, message?: string) => asserts value is T;
Assert that a value passes a struct, throwing if it doesn't.
function assign
assign: { <A extends ObjectSchema, B extends ObjectSchema>( A: Struct<ObjectType<A>, A>, B: Struct<ObjectType<B>, B> ): Struct<ObjectType<Assign<A, B>>, Assign<A, B>>; <A extends ObjectSchema, B extends ObjectSchema, C extends ObjectSchema>( A: Struct<Simplify<Optionalize<{ [K in keyof A]: Infer<A[K]> }>>, A>, B: Struct<Simplify<Optionalize<{ [K in keyof B]: Infer<B[K]> }>>, B>, C: Struct<Simplify<Optionalize<{ [K in keyof C]: Infer<C[K]> }>>, C> ): Struct< Simplify< Optionalize<{ [K in keyof Simplify< C & Omit<Simplify<B & Omit<A, keyof B>>, keyof C> >]: Infer< Simplify<C & Omit<Simplify<B & Omit<A, keyof B>>, keyof C>>[K] >; }> >, Simplify<C & Omit<Simplify<B & Omit<A, keyof B>>, keyof C>> >; < A extends ObjectSchema, B extends ObjectSchema, C extends ObjectSchema, D extends ObjectSchema >( A: Struct<Simplify<Optionalize<{ [K in keyof A]: Infer<A[K]> }>>, A>, B: Struct<Simplify<Optionalize<{ [K in keyof B]: Infer<B[K]> }>>, B>, C: Struct<Simplify<Optionalize<{ [K in keyof C]: Infer<C[K]> }>>, C>, D: Struct<Simplify<Optionalize<{ [K in keyof D]: Infer<D[K]> }>>, D> ): Struct< Simplify< Optionalize<{ [K in keyof Simplify< D & Omit< Simplify< C & Omit<Simplify<B & Omit<A, keyof B>>, keyof C> >, keyof D > >]: Infer< Simplify< D & Omit< Simplify< C & Omit<Simplify<B & Omit<A, keyof B>>, keyof C> >, keyof D > >[K] >; }> >, Simplify< D & Omit< Simplify<C & Omit<Simplify<B & Omit<A, keyof B>>, keyof C>>, keyof D > > >; < A extends ObjectSchema, B extends ObjectSchema, C extends ObjectSchema, D extends ObjectSchema, E extends ObjectSchema >( A: Struct<Simplify<Optionalize<{ [K in keyof A]: Infer<A[K]> }>>, A>, B: Struct<Simplify<Optionalize<{ [K in keyof B]: Infer<B[K]> }>>, B>, C: Struct<Simplify<Optionalize<{ [K in keyof C]: Infer<C[K]> }>>, C>, D: Struct<Simplify<Optionalize<{ [K in keyof D]: Infer<D[K]> }>>, D>, E: Struct<Simplify<Optionalize<{ [K in keyof E]: Infer<E[K]> }>>, E> ): Struct< Simplify< Optionalize<{ [K in keyof Simplify< E & Omit< Simplify< D & Omit< Simplify< C & Omit< Simplify<B & Omit<A, keyof B>>, keyof C > >, keyof D > >, keyof E > >]: Infer< Simplify< E & Omit< Simplify< D & Omit< Simplify< C & Omit< Simplify< B & Omit<A, keyof B> >, keyof C > >, keyof D > >, keyof E > >[K] >; }> >, Simplify< E & Omit< Simplify< D & Omit< Simplify< C & Omit<Simplify<B & Omit<A, keyof B>>, keyof C> >, keyof D > >, keyof E > > >;};
Create a new struct that combines the properties properties from multiple object or type structs. Its return type will match the first parameter's type.
Like JavaScript's
Object.assign
utility.
function bigint
bigint: () => Struct<bigint, null>;
Ensure that a value is a bigint.
function boolean
boolean: () => Struct<boolean, null>;
Ensure that a value is a boolean.
function coerce
coerce: <T, S, C>( struct: Struct<T, S>, condition: Struct<C, any>, coercer: Coercer<C>) => Struct<T, S>;
Augment a
Struct
to add an additional coercion step to its input.This allows you to transform input data before validating it, to increase the likelihood that it passes validation—for example for default values, parsing different formats, etc.
Note: You must use
create(value, Struct)
on the value to have the coercion take effect! Using simplyassert()
oris()
will not use coercion.
function create
create: <T, S>(value: unknown, struct: Struct<T, S>, message?: string) => T;
Create a value with the coercion logic of struct and validate it.
function date
date: () => Struct<Date, null>;
Ensure that a value is a valid
Date
.Note: this also ensures that the value is *not* an invalid
Date
object, which can occur when parsing a date fails but still returns aDate
.
function defaulted
defaulted: <T, S>( struct: Struct<T, S>, fallback: any, options?: { strict?: boolean }) => Struct<T, S>;
Augment a struct to replace
undefined
values with a default.Note: You must use
create(value, Struct)
on the value to have the coercion take effect! Using simplyassert()
oris()
will not use coercion.
function define
define: <T>(name: string, validator: Validator) => Struct<T, null>;
Define a new struct type with a custom validation function.
function deprecated
deprecated: <T>( struct: Struct<T>, log: (value: unknown, ctx: Context) => void) => Struct<T>;
Create a new struct based on an existing struct, but the value is allowed to be
undefined
.log
will be called if the value is notundefined
.
function dynamic
dynamic: <T>( fn: (value: unknown, ctx: Context) => Struct<T, any>) => Struct<T, null>;
Create a struct with dynamic validation logic.
The callback will receive the value currently being validated, and must return a struct object to validate it with. This can be useful to model validation logic that changes based on its input.
function empty
empty: <T extends string | any[] | Map<any, any> | Set<any>, S extends unknown>( struct: Struct<T, S>) => Struct<T, S>;
Ensure that a string, array, map, or set is empty.
function enums
enums: { <U extends number, T extends readonly U[]>(values: T): Struct< T[number], { [K in T[number]]: K } >; <U extends string, T extends readonly U[]>(values: T): Struct< T[number], { [K in T[number]]: K } >;};
Ensure that a value is one of a set of potential values.
Note: after creating the struct, you can access the definition of the potential values as
struct.schema
.
function func
func: () => Struct<Function, null>;
Ensure that a value is a function.
function instance
instance: <T extends new (...args: any) => any>( Class: T) => Struct<InstanceType<T>, null>;
Ensure that a value is an instance of a specific class.
function integer
integer: () => Struct<number, null>;
Ensure that a value is an integer.
function intersection
intersection: <A extends AnyStruct, B extends AnyStruct[]>( Structs: [A, ...B]) => Struct<Infer<A> & UnionToIntersection<InferStructTuple<B>[number]>, null>;
Ensure that a value matches all of a set of types.
function is
is: <T, S>(value: unknown, struct: Struct<T, S>) => value is T;
Check if a value passes a struct.
function lazy
lazy: <T>(fn: () => Struct<T, any>) => Struct<T, null>;
Create a struct with lazily evaluated validation logic.
The first time validation is run with the struct, the callback will be called and must return a struct object to use. This is useful for cases where you want to have self-referential structs for nested data structures to avoid a circular definition problem.
function literal
literal: { <T extends boolean>(constant: T): Struct<T, T>; <T extends number>(constant: T): Struct<T, T>; <T extends string>(constant: T): Struct<T, T>; <T>(constant: T): Struct<T, null>;};
Ensure that a value is an exact value, using
===
for comparison.
function map
map: { (): Struct<Map<unknown, unknown>, null>; <K, V>(Key: Struct<K, unknown>, Value: Struct<V, unknown>): Struct< Map<K, V>, null >;};
Ensure that a value is a
Map
object, and that its keys and values are of specific types.
function mask
mask: <T, S>(value: unknown, struct: Struct<T, S>, message?: string) => T;
Mask a value, returning only the subset of properties defined by a struct.
function max
max: <T extends number | Date, S extends unknown>( struct: Struct<T, S>, threshold: T, options?: { exclusive?: boolean }) => Struct<T, S>;
Ensure that a number or date is below a threshold.
function min
min: <T extends number | Date, S extends unknown>( struct: Struct<T, S>, threshold: T, options?: { exclusive?: boolean }) => Struct<T, S>;
Ensure that a number or date is above a threshold.
function never
never: () => Struct<never, null>;
Ensure that no value ever passes validation.
function nonempty
nonempty: < T extends string | any[] | Map<any, any> | Set<any>, S extends unknown>( struct: Struct<T, S>) => Struct<T, S>;
Ensure that a string, array, map or set is not empty.
function nullable
nullable: <T, S>(struct: Struct<T, S>) => Struct<T | null, S>;
Augment an existing struct to allow
null
values.
function number
number: () => Struct<number, null>;
Ensure that a value is a number.
function object
object: { (): Struct<Record<string, unknown>, null>; <S extends ObjectSchema>(schema: S): Struct< Simplify<Optionalize<{ [K in keyof S]: Infer<S[K]> }>>, S >;};
Ensure that a value is an object, that is has a known set of properties, and that its properties are of specific types.
Note: Unrecognized properties will fail validation.
function omit
omit: <S extends ObjectSchema, K extends keyof S>( struct: Struct<ObjectType<S>, S>, keys: K[]) => Struct<ObjectType<Omit<S, K>>, Omit<S, K>>;
Create a new struct based on an existing object struct, but excluding specific properties.
Like TypeScript's
Omit
utility.
function optional
optional: <T, S>(struct: Struct<T, S>) => Struct<T | undefined, S>;
Augment a struct to allow
undefined
values.
function partial
partial: <S extends ObjectSchema>( struct: Struct<ObjectType<S>, S> | S) => Struct<ObjectType<PartialObjectSchema<S>>, PartialObjectSchema<S>>;
Create a new struct based on an existing object struct, but with all of its properties allowed to be
undefined
.Like TypeScript's
Partial
utility.
function pattern
pattern: <T extends string, S extends unknown>( struct: Struct<T, S>, regexp: RegExp) => Struct<T, S>;
Ensure that a string matches a regular expression.
function pick
pick: <S extends ObjectSchema, K extends keyof S>( struct: Struct<ObjectType<S>, S>, keys: K[]) => Struct<ObjectType<Pick<S, K>>, Pick<S, K>>;
Create a new struct based on an existing object struct, but only including specific properties.
Like TypeScript's
Pick
utility.
function record
record: <K extends string, V>( Key: Struct<K>, Value: Struct<V>) => Struct<Record<K, V>, null>;
Ensure that a value is an object with keys and values of specific types, but without ensuring any specific shape of properties.
Like TypeScript's
Record
utility.
function refine
refine: <T, S>( struct: Struct<T, S>, name: string, refiner: Refiner<T>) => Struct<T, S>;
Augment a
Struct
to add an additional refinement to the validation.The refiner function is guaranteed to receive a value of the struct's type, because the struct's existing validation will already have passed. This allows you to layer additional validation on top of existing structs.
function regexp
regexp: () => Struct<RegExp, null>;
Ensure that a value is a
RegExp
.Note: this does not test the value against the regular expression! For that you need to use the
pattern()
refinement.
function set
set: { (): Struct<Set<unknown>, null>; <T>(Element: Struct<T, unknown>): Struct<Set<T>, null>;};
Ensure that a value is a
Set
object, and that its elements are of a specific type.
function size
size: < T extends string | number | any[] | Map<any, any> | Set<any> | Date, S extends unknown>( struct: Struct<T, S>, min: number, max?: number) => Struct<T, S>;
Ensure that a string, array, number, date, map, or set has a size (or length, or time) between
min
andmax
.
function string
string: () => Struct<string, null>;
Ensure that a value is a string.
function struct
struct: <T>(name: string, validator: Validator) => Struct<T, null>;
Define a new struct type with a custom validation function.
Deprecated
This function has been renamed to
define
.
function trimmed
trimmed: <T, S>(struct: Struct<T, S>) => Struct<T, S>;
Augment a struct to trim string inputs.
Note: You must use
create(value, Struct)
on the value to have the coercion take effect! Using simplyassert()
oris()
will not use coercion.
function tuple
tuple: <A extends AnyStruct, B extends AnyStruct[]>( Structs: [A, ...B]) => Struct<[Infer<A>, ...InferStructTuple<B>], null>;
Ensure that a value is a tuple of a specific length, and that each of its elements is of a specific type.
function type
type: <S extends ObjectSchema>(schema: S) => Struct<ObjectType<S>, S>;
Ensure that a value has a set of known properties of specific types.
Note: Unrecognized properties are allowed and untouched. This is similar to how TypeScript's structural typing works.
function union
union: <A extends AnyStruct, B extends AnyStruct[]>( Structs: [A, ...B]) => Struct<Infer<A> | InferStructTuple<B>[number], null>;
Ensure that a value matches one of a set of types.
function unknown
unknown: () => Struct<unknown, null>;
Ensure that any value passes validation, without widening its type to
any
.
function validate
validate: <T, S>( value: unknown, struct: Struct<T, S>, options?: { coerce?: boolean; mask?: boolean; message?: string }) => [StructError, undefined] | [undefined, T];
Validate a value against a struct, returning an error if invalid, or the value (with potential coercion) if valid.
Classes
class Struct
class Struct<T = unknown, S = unknown> {}
Struct
objects encapsulate the validation logic for a specific type of values. Once constructed, you use theassert
,is
orvalidate
helpers to validate unknown input data against the struct.
constructor
constructor(props: { type: string; schema: S; coercer?: Coercer; validator?: Validator; refiner?: Refiner<T>; entries?: Struct<T, S>['entries'];});
property coercer
coercer: (value: unknown, context: Context) => unknown;
property entries
entries: ( value: unknown, context: Context) => Iterable<[string | number, unknown, Struct<any> | Struct<never>]>;
property refiner
refiner: (value: T, context: Context) => Iterable<Failure>;
property schema
schema: {};
property type
type: string;
property TYPE
readonly TYPE: {};
property validator
validator: (value: unknown, context: Context) => Iterable<Failure>;
method assert
assert: (value: unknown, message?: string) => asserts value is T;
Assert that a value passes the struct's validation, throwing if it doesn't.
method create
create: (value: unknown, message?: string) => T;
Create a value with the struct's coercion logic, then validate it.
method is
is: (value: unknown) => value is T;
Check if a value passes the struct's validation.
method mask
mask: (value: unknown, message?: string) => T;
Mask a value, coercing and validating it, but returning only the subset of properties defined by the struct's schema. Masking applies recursively to props of
object
structs only.
method validate
validate: ( value: unknown, options?: { coerce?: boolean; mask?: boolean; message?: string }) => [StructError, undefined] | [undefined, T];
Validate a value with the struct's validation logic, returning a tuple representing the result.
You may optionally pass
true
for thecoerce
argument to coerce the value before attempting to validate it. If you do, the result will contain the coerced result when successful. Also,mask
will turn on masking of the unknownobject
props recursively if passed.
class StructError
class StructError extends TypeError {}
StructError
objects are thrown (or returned) when validation fails.Validation logic is design to exit early for maximum performance. The error represents the first error encountered during validation. For more detail, the
error.failures
property is a generator function that can be run to continue validation and receive all the failures in the data.
constructor
constructor(failure: Failure, failures: () => Generator<Failure>);
property branch
branch: any[];
property failures
failures: () => Array<Failure>;
property key
key: any;
property path
path: any[];
property refinement
refinement: string;
property type
type: string;
property value
value: any;
Type Aliases
type Coercer
type Coercer<T = unknown> = (value: T, context: Context) => unknown;
A
Coercer
takes an unknown value and optionally coerces it.
type Context
type Context = { branch: Array<any>; path: Array<any>; mask?: boolean;};
A
Context
contains information about the current location of the validation inside the initial input value. It also carriesmask
since it's a run-time flag determining how the validation was invoked (viamask()
or viavalidate()
), plus it applies recursively to all of the nested structs.
type Describe
type Describe<T> = Struct<T, StructSchema<T>>;
A type utility to describe that a struct represents a TypeScript type.
type Failure
type Failure = { value: any; key: any; type: string; refinement: string | undefined; message: string; explanation?: string; branch: Array<any>; path: Array<any>;};
A
StructFailure
represents a single specific failure in validation.
type Infer
type Infer<T extends Struct<any, any>> = T['TYPE'];
A type utility to extract the type from a
Struct
class.
type Refiner
type Refiner<T> = (value: T, context: Context) => Result;
A
Refiner
takes a value of a known type and validates it against a further constraint.
type Result
type Result = | boolean | string | Partial<Failure> | Iterable<boolean | string | Partial<Failure>>;
A
Result
is returned from validation functions.
type Validator
type Validator = (value: unknown, context: Context) => Result;
A
Validator
takes an unknown value and validates it.
Package Files (7)
Dependencies (0)
No dependencies.
Dev Dependencies (15)
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/superstruct
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/superstruct)
- HTML<a href="https://www.jsdocs.io/package/superstruct"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5980 ms. - Missing or incorrect documentation? Open an issue for this package.