ow

  • Version 3.1.1
  • Published
  • 154 kB
  • 6 dependencies
  • MIT license

Install

npm i ow
yarn add ow
pnpm add ow

Overview

Function argument validation for humans

Index

Variables

Functions

Classes

Type Aliases

Variables

variable _ow

const _ow: Ow;

    Functions

    function isPredicate

    isPredicate: (value: unknown) => value is BasePredicate<unknown>;

    Classes

    class AnyPredicate

    class AnyPredicate<T = unknown> implements BasePredicate<T> {}

    constructor

    constructor(predicates: BasePredicate<unknown>[], options?: PredicateOptions);

      property [nullableSymbol]

      [nullableSymbol]?: boolean;

        property [optionalSymbol]

        [optionalSymbol]?: boolean;

          method [testSymbol]

          [testSymbol]: (
          value: T,
          main: Main,
          label: string | Function,
          idLabel: boolean
          ) => asserts value;

            class ArgumentError

            class ArgumentError extends Error {}

            constructor

            constructor(
            message: string,
            context: Function,
            errors?: Map<string, Set<string>>
            );

              property validationErrors

              readonly validationErrors: ReadonlyMap<string, Set<string>>;

                class ArrayBufferPredicate

                class ArrayBufferPredicate<T extends ArrayBufferLike> extends Predicate<T> {}

                  constructor

                  constructor(
                  type: string,
                  options?: PredicateOptions,
                  validators?: Validator<T>[]
                  );

                  method byteLength

                  byteLength: (byteLength: number) => this;
                  • Test an array buffer to have a specific byte length.

                    Parameter byteLength

                    The byte length of the array buffer.

                  method maxByteLength

                  maxByteLength: (byteLength: number) => this;
                  • Test an array buffer to have a minimum byte length.

                    Parameter length

                    The minimum byte length of the array buffer.

                  method minByteLength

                  minByteLength: (byteLength: number) => this;
                  • Test an array buffer to have a minimum byte length.

                    Parameter byteLength

                    The minimum byte length of the array buffer.

                  method withValidators

                  protected withValidators: (validators: Array<Validator<T>>) => this;

                  class ArrayPredicate

                  class ArrayPredicate<T = unknown> extends Predicate<T[]> {}

                    constructor

                    constructor(options?: PredicateOptions, validators?: Validator<T[]>[]);

                    property empty

                    readonly empty: ArrayPredicate<T>;
                    • Test an array to be empty.

                    property nonEmpty

                    readonly nonEmpty: ArrayPredicate<T>;
                    • Test an array to be not empty.

                    method deepEqual

                    deepEqual: (expected: readonly T[]) => this;
                    • Test an array to be deeply equal to the provided array.

                      Parameter expected

                      Expected value to match.

                    method endsWith

                    endsWith: (searchElement: T) => this;
                    • Test an array to end with a specific value. The value is tested by identity, not structure.

                      Parameter searchElement

                      The value that should be the end of the array.

                    method exactShape

                    exactShape: (predicates: BasePredicate[]) => this;
                    • Test if the elements in the array exactly matches the elements placed at the same indices in the predicates array.

                      Parameter predicates

                      Predicates to test the array against. Describes what the tested array should look like.

                      Example 1

                      ``` ow(['1', 2], ow.array.exactShape([ow.string, ow.number])); ```

                    method includes

                    includes: (...searchElements: readonly T[]) => this;
                    • Test an array to include all the provided elements. The values are tested by identity, not structure.

                      Parameter searchElements

                      The values that should be included in the array.

                    method includesAny

                    includesAny: (...searchElements: readonly T[]) => this;
                    • Test an array to include any of the provided elements. The values are tested by identity, not structure.

                      Parameter searchElements

                      The values that should be included in the array.

                    method length

                    length: (length: number) => this;
                    • Test an array to have a specific length.

                      Parameter length

                      The length of the array.

                    method maxLength

                    maxLength: (length: number) => this;
                    • Test an array to have a maximum length.

                      Parameter length

                      The maximum length of the array.

                    method minLength

                    minLength: (length: number) => this;
                    • Test an array to have a minimum length.

                      Parameter length

                      The minimum length of the array.

                    method ofType

                    ofType: <U extends T>(predicate: BasePredicate<U>) => ArrayPredicate<U>;
                    • Test all elements in the array to match to provided predicate.

                      Parameter predicate

                      The predicate that should be applied against every individual item.

                      Example 1

                      ``` ow(['a', 1], ow.array.ofType(ow.any(ow.string, ow.number))); ```

                    method startsWith

                    startsWith: (searchElement: T) => this;
                    • Test an array to start with a specific value. The value is tested by identity, not structure.

                      Parameter searchElement

                      The value that should be the start of the array.

                    class BigIntPredicate

                    class BigIntPredicate extends Predicate<bigint> {}

                      constructor

                      constructor(options?: PredicateOptions, validators?: Validator<bigint>[]);

                      class BooleanPredicate

                      class BooleanPredicate extends Predicate<boolean> {}

                        constructor

                        constructor(options?: PredicateOptions, validators?: Validator<boolean>[]);

                        property false

                        readonly false: BooleanPredicate;
                        • Test a boolean to be false.

                        property true

                        readonly true: BooleanPredicate;
                        • Test a boolean to be true.

                        class DataViewPredicate

                        class DataViewPredicate extends Predicate<DataView> {}

                          constructor

                          constructor(options?: PredicateOptions, validators?: Validator<DataView>[]);

                          method byteLength

                          byteLength: (byteLength: number) => this;
                          • Test a DataView to have a specific byte length.

                            Parameter byteLength

                            The byte length of the DataView.

                          method maxByteLength

                          maxByteLength: (byteLength: number) => this;
                          • Test a DataView to have a minimum byte length.

                            Parameter length

                            The minimum byte length of the DataView.

                          method minByteLength

                          minByteLength: (byteLength: number) => this;
                          • Test a DataView to have a minimum byte length.

                            Parameter byteLength

                            The minimum byte length of the DataView.

                          class DatePredicate

                          class DatePredicate extends Predicate<Date> {}

                            constructor

                            constructor(options?: PredicateOptions, validators?: Validator<Date>[]);

                            method after

                            after: (date: Date) => this;
                            • Test a date to be before another date.

                              Parameter date

                              Minimum value.

                            method before

                            before: (date: Date) => this;
                            • Test a date to be before another date.

                              Parameter date

                              Maximum value.

                            class ErrorPredicate

                            class ErrorPredicate extends Predicate<Error> {}

                              constructor

                              constructor(options?: PredicateOptions, validators?: Validator<Error>[]);

                              property evalError

                              readonly evalError: ErrorPredicate;
                              • Test an Error to be an EvalError.

                              property rangeError

                              readonly rangeError: ErrorPredicate;
                              • Test an Error to be a RangeError.

                              property referenceError

                              readonly referenceError: ErrorPredicate;
                              • Test an Error to be a ReferenceError.

                              property syntaxError

                              readonly syntaxError: ErrorPredicate;
                              • Test an Error to be a SyntaxError.

                              property typeError

                              readonly typeError: ErrorPredicate;
                              • Test an Error to be a TypeError.

                              property uriError

                              readonly uriError: ErrorPredicate;
                              • Test an Error to be a URIError.

                              method hasKeys

                              hasKeys: (...keys: readonly string[]) => this;
                              • Test the error object to have specific keys.

                                Parameter keys

                                One or more keys which should be part of the error object.

                              method instanceOf

                              instanceOf: (instance: Function) => this;
                              • Test an error to be of a specific instance type.

                                Parameter instance

                                The expected instance type of the error.

                              method message

                              message: (expected: string) => this;
                              • Test an error to have a specific message.

                                Parameter expected

                                Expected message of the Error.

                              method messageIncludes

                              messageIncludes: (message: string) => this;
                              • Test the error message to include a specific message.

                                Parameter message

                                Message that should be included in the error.

                              method name

                              name: (expected: string) => this;
                              • Test an error to have a specific name.

                                Parameter expected

                                Expected name of the Error.

                              class MapPredicate

                              class MapPredicate<T1 = unknown, T2 = unknown> extends Predicate<Map<T1, T2>> {}

                                constructor

                                constructor(options?: PredicateOptions, validators?: Validator<Map<T1, T2>>[]);

                                property empty

                                readonly empty: MapPredicate<T1, T2>;
                                • Test a Map to be empty.

                                property nonEmpty

                                readonly nonEmpty: MapPredicate<T1, T2>;
                                • Test a Map to be not empty.

                                method deepEqual

                                deepEqual: (expected: Map<T1, T2>) => this;
                                • Test a Map to be deeply equal to the provided Map.

                                  Parameter expected

                                  Expected Map to match.

                                method hasAnyKeys

                                hasAnyKeys: (...keys: readonly T1[]) => this;
                                • Test a Map to include any of the provided keys. The keys are tested by identity, not structure.

                                  Parameter keys

                                  The keys that could be a key in the Map.

                                method hasAnyValues

                                hasAnyValues: (...values: readonly T2[]) => this;
                                • Test a Map to include any of the provided values. The values are tested by identity, not structure.

                                  Parameter values

                                  The values that could be a value in the Map.

                                method hasKeys

                                hasKeys: (...keys: readonly T1[]) => this;
                                • Test a Map to include all the provided keys. The keys are tested by identity, not structure.

                                  Parameter keys

                                  The keys that should be a key in the Map.

                                method hasValues

                                hasValues: (...values: readonly T2[]) => this;
                                • Test a Map to include all the provided values. The values are tested by identity, not structure.

                                  Parameter values

                                  The values that should be a value in the Map.

                                method keysOfType

                                keysOfType: (predicate: BasePredicate<T1>) => this;
                                • Test all the keys in the Map to match the provided predicate.

                                  Parameter predicate

                                  The predicate that should be applied against every key in the Map.

                                method maxSize

                                maxSize: (size: number) => this;
                                • Test an Map to have a maximum size.

                                  Parameter size

                                  The maximum size of the Map.

                                method minSize

                                minSize: (size: number) => this;
                                • Test an Map to have a minimum size.

                                  Parameter size

                                  The minimum size of the Map.

                                method size

                                size: (size: number) => this;
                                • Test a Map to have a specific size.

                                  Parameter size

                                  The size of the Map.

                                method valuesOfType

                                valuesOfType: (predicate: BasePredicate<T2>) => this;
                                • Test all the values in the Map to match the provided predicate.

                                  Parameter predicate

                                  The predicate that should be applied against every value in the Map.

                                class NumberPredicate

                                class NumberPredicate extends Predicate<number> {}

                                  constructor

                                  constructor(options?: PredicateOptions, validators?: Validator<number>[]);

                                  property finite

                                  readonly finite: NumberPredicate;
                                  • Test a number to be finite.

                                  property infinite

                                  readonly infinite: NumberPredicate;
                                  • Test a number to be infinite.

                                  property int16

                                  readonly int16: NumberPredicate;
                                  • Test a number to be in a valid range for a 16-bit signed integer.

                                  property int32

                                  readonly int32: NumberPredicate;
                                  • Test a number to be in a valid range for a 32-bit signed integer.

                                  property int8

                                  readonly int8: NumberPredicate;
                                  • Test a number to be in a valid range for a 8-bit signed integer.

                                  property integer

                                  readonly integer: NumberPredicate;
                                  • Test a number to be an integer.

                                  property integerOrInfinite

                                  readonly integerOrInfinite: NumberPredicate;
                                  • Test a number to be an integer or infinite.

                                  property negative

                                  readonly negative: NumberPredicate;
                                  • Test a number to be negative.

                                  property positive

                                  readonly positive: NumberPredicate;
                                  • Test a number to be positive.

                                  property uint16

                                  readonly uint16: NumberPredicate;
                                  • Test a number to be in a valid range for a 16-bit unsigned integer.

                                  property uint32

                                  readonly uint32: NumberPredicate;
                                  • Test a number to be in a valid range for a 32-bit unsigned integer.

                                  property uint8

                                  readonly uint8: NumberPredicate;
                                  • Test a number to be in a valid range for a 8-bit unsigned integer.

                                  method equal

                                  equal: (expected: number) => this;
                                  • Test a number to be equal to a specified number.

                                    Parameter expected

                                    Expected value to match.

                                  method greaterThan

                                  greaterThan: (number: number) => this;
                                  • Test a number to be greater than the provided value.

                                    Parameter number

                                    Minimum value.

                                  method greaterThanOrEqual

                                  greaterThanOrEqual: (number: number) => this;
                                  • Test a number to be greater than or equal to the provided value.

                                    Parameter number

                                    Minimum value.

                                  method inRange

                                  inRange: (start: number, end: number) => this;
                                  • Test a number to be in a specified range.

                                    Parameter start

                                    Start of the range.

                                    Parameter end

                                    End of the range.

                                  method lessThan

                                  lessThan: (number: number) => this;
                                  • Test a number to be less than the provided value.

                                    Parameter number

                                    Maximum value.

                                  method lessThanOrEqual

                                  lessThanOrEqual: (number: number) => this;
                                  • Test a number to be less than or equal to the provided value.

                                    Parameter number

                                    Minimum value.

                                  method oneOf

                                  oneOf: (list: readonly number[]) => this;
                                  • Test if a number is an element of the provided list.

                                    Parameter list

                                    List of possible values.

                                  class ObjectPredicate

                                  class ObjectPredicate<T extends object = object> extends Predicate<T> {}

                                    constructor

                                    constructor(options?: PredicateOptions, validators?: Validator<T>[]);

                                    property empty

                                    readonly empty: ObjectPredicate<T>;
                                    • Test an object to be empty.

                                    property nonEmpty

                                    readonly nonEmpty: ObjectPredicate<T>;
                                    • Test an object to be not empty.

                                    property plain

                                    readonly plain: ObjectPredicate<T>;
                                    • Test if an Object is a plain object.

                                    method deepEqual

                                    deepEqual: (expected: object) => this;
                                    • Test an object to be deeply equal to the provided object.

                                      Parameter expected

                                      Expected object to match.

                                    method deepValuesOfType

                                    deepValuesOfType: <T>(predicate: Predicate<T>) => this;
                                    • Test all the values in the object deeply to match the provided predicate.

                                      Parameter predicate

                                      The predicate that should be applied against every value in the object.

                                    method exactShape

                                    exactShape: <S extends Shape = Shape>(
                                    shape: S
                                    ) => ObjectPredicate<TypeOfShape<S>>;
                                    • Test an object to match the shape exactly. This means that will fail if it comes across unexpected properties. The shape comparison is deep.

                                      The shape is an object which describes how the tested object should look like. The keys are the same as the source object and the values are predicates.

                                      Parameter shape

                                      Shape to test the object against.

                                      Example 1

                                      ``` import ow from 'ow';

                                      ow({unicorn: '🦄'}, ow.object.exactShape({ unicorn: ow.string })); ```

                                    method hasAnyKeys

                                    hasAnyKeys: (...keys: readonly string[]) => this;
                                    • Test an object to include any of the provided keys. You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a key to access nested properties.

                                      Parameter keys

                                      The keys that could be a key in the object.

                                    method hasKeys

                                    hasKeys: (...keys: readonly string[]) => this;
                                    • Test an object to include all the provided keys. You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a key to access nested properties.

                                      Parameter keys

                                      The keys that should be present in the object.

                                    method instanceOf

                                    instanceOf: (instance: Function) => this;
                                    • Test an object to be of a specific instance type.

                                      Parameter instance

                                      The expected instance type of the object.

                                    method partialShape

                                    partialShape: <S extends Shape = Shape>(
                                    shape: S
                                    ) => ObjectPredicate<TypeOfShape<S>>;
                                    • Test an object to match the shape partially. This means that it ignores unexpected properties. The shape comparison is deep.

                                      The shape is an object which describes how the tested object should look like. The keys are the same as the source object and the values are predicates.

                                      Parameter shape

                                      Shape to test the object against.

                                      Example 1

                                      ``` import ow from 'ow';

                                      const object = { unicorn: '🦄', rainbow: '🌈' };

                                      ow(object, ow.object.partialShape({ unicorn: ow.string })); ```

                                    method valuesOfType

                                    valuesOfType: <T>(predicate: BasePredicate<T>) => this;
                                    • Test all the values in the object to match the provided predicate.

                                      Parameter predicate

                                      The predicate that should be applied against every value in the object.

                                    class Predicate

                                    class Predicate<T = unknown> implements BasePredicate<T> {}

                                    constructor

                                    constructor(
                                    type: string,
                                    options?: PredicateOptions,
                                    existingValidators?: Validator<T>[]
                                    );

                                      property [absentSymbol]

                                      [absentSymbol]?: boolean;

                                        property [nullableSymbol]

                                        [nullableSymbol]?: boolean;

                                          property [optionalSymbol]

                                          [optionalSymbol]?: boolean;

                                            property [validatorSymbol]

                                            readonly [validatorSymbol]: Validator<T>[];

                                            property not

                                            readonly not: Predicate<T>;
                                            • Invert the following validators.

                                            property options

                                            protected readonly options: PredicateOptions;

                                              method [testSymbol]

                                              [testSymbol]: (
                                              value: T,
                                              main: Main,
                                              label: string | (() => string),
                                              idLabel: boolean
                                              ) => asserts value is T;

                                              method addValidator

                                              addValidator: (validator: Validator<T>) => this;
                                              • Register a new validator.

                                                Parameter validator

                                                Validator to register.

                                              method custom

                                              custom: (customValidator: (value: T) => void) => this;
                                              • Use a custom validation function that throws an error when the validation fails. This is useful for reusing existing validators or composing complex validations.

                                                Parameter customValidator

                                                Custom validation function that throws an error if the value is invalid.

                                                Example 1

                                                ``` import ow from 'ow';

                                                interface User { name: string; age: number; }

                                                const validateUser = (user: User) => { ow(user.name, 'User.name', ow.string.nonEmpty); ow(user.age, 'User.age', ow.number.integer.positive); };

                                                ow([{name: 'Alice', age: 30}], ow.array.ofType(ow.object.custom(validateUser))); ```

                                                Example 2

                                                This is particularly useful when you have existing validation functions and want to compose them:

                                                ``` import ow from 'ow';

                                                interface Animal { type: string; weight: number; }

                                                const validateAnimal = (animal: Animal) => { ow(animal.type, 'Animal.type', ow.string.oneOf(['dog', 'cat', 'elephant'])); ow(animal.weight, 'Animal.weight', ow.number.finite.positive); };

                                                const animals: Animal[] = [ {type: 'dog', weight: 5}, {type: 'cat', weight: Number.POSITIVE_INFINITY} ];

                                                ow(animals, ow.array.ofType(ow.object.custom(validateAnimal))); //=> ArgumentError: (array) (object) Expected number Animal.weight to be finite, got Infinity ```

                                              method is

                                              is: (validator: (value: T) => boolean | string) => this;
                                              • Test if the value matches a custom validation function. The validation function should return true if the value passes the function. If the function either returns false or a string, the function fails and the string will be used as error message.

                                                Parameter validator

                                                Validation function.

                                              method message

                                              message: (newMessage: string | ValidatorMessageBuilder<T>) => this;
                                              • Provide a new error message to be thrown when the validation fails.

                                                Parameter newMessage

                                                Either a string containing the new message or a function returning the new message.

                                                Example 1

                                                ``` ow('🌈', 'unicorn', ow.string.equals('🦄').message('Expected unicorn, got rainbow')); //=> ArgumentError: Expected unicorn, got rainbow ```

                                                Example 2

                                                ``` ow('🌈', ow.string.minLength(5).message((value, label) => Expected ${label}, to have a minimum length of 5, got \${value}``)); //=> ArgumentError: Expected string, to be have a minimum length of 5, got 🌈 ```

                                              method validate

                                              validate: (customValidator: CustomValidator<T>) => this;
                                              • Test if the value matches a custom validation function. The validation function should return an object containing a validator and message. If the validator is false, the validation fails and the message will be used as error message. If the message is a function, the function is invoked with the label as argument to let you further customize the error message.

                                                Parameter customValidator

                                                Custom validation function.

                                              method withValidators

                                              protected withValidators: (validators: Array<Validator<T>>) => this;
                                              • Create a new instance with the given validators

                                              class SetPredicate

                                              class SetPredicate<T = unknown> extends Predicate<Set<T>> {}

                                                constructor

                                                constructor(options?: PredicateOptions, validators?: Validator<Set<T>>[]);

                                                property empty

                                                readonly empty: SetPredicate<T>;
                                                • Test a Set to be empty.

                                                property nonEmpty

                                                readonly nonEmpty: SetPredicate<T>;
                                                • Test a Set to be not empty.

                                                method deepEqual

                                                deepEqual: (expected: Set<T>) => this;
                                                • Test a Set to be deeply equal to the provided Set.

                                                  Parameter expected

                                                  Expected Set to match.

                                                method has

                                                has: (...items: readonly T[]) => this;
                                                • Test a Set to include all the provided items. The items are tested by identity, not structure.

                                                  Parameter items

                                                  The items that should be a item in the Set.

                                                method hasAny

                                                hasAny: (...items: readonly T[]) => this;
                                                • Test a Set to include any of the provided items. The items are tested by identity, not structure.

                                                  Parameter items

                                                  The items that could be a item in the Set.

                                                method maxSize

                                                maxSize: (size: number) => this;
                                                • Test a Set to have a maximum size.

                                                  Parameter size

                                                  The maximum size of the Set.

                                                method minSize

                                                minSize: (size: number) => this;
                                                • Test a Set to have a minimum size.

                                                  Parameter size

                                                  The minimum size of the Set.

                                                method ofType

                                                ofType: (predicate: BasePredicate<T>) => this;
                                                • Test all the items in the Set to match the provided predicate.

                                                  Parameter predicate

                                                  The predicate that should be applied against every item in the Set.

                                                method size

                                                size: (size: number) => this;
                                                • Test a Set to have a specific size.

                                                  Parameter size

                                                  The size of the Set.

                                                class StringPredicate

                                                class StringPredicate extends Predicate<string> {}

                                                  constructor

                                                  constructor(options?: PredicateOptions, validators?: Validator<string>[]);

                                                  property alphabetical

                                                  readonly alphabetical: StringPredicate;
                                                  • Test a string to be alphabetical.

                                                  property alphanumeric

                                                  readonly alphanumeric: StringPredicate;
                                                  • Test a string to be alphanumeric.

                                                  property date

                                                  readonly date: StringPredicate;
                                                  • Test a string to be a valid date.

                                                  property email

                                                  readonly email: StringPredicate;
                                                  • Test a string to be a valid email address.

                                                    The validation is based on a practical subset of RFC 5322 that works for real-world email addresses. This implementation balances strictness with usability and performance.

                                                    Example 1

                                                    ``` import ow from 'ow';

                                                    ow('foo@example.com', ow.string.email); //=> passes

                                                    ow('invalid.email', ow.string.email); //=> ArgumentError: Expected string to be an email address, got invalid.email ```

                                                  property empty

                                                  readonly empty: StringPredicate;
                                                  • Test a string to be empty.

                                                  property lowercase

                                                  readonly lowercase: StringPredicate;
                                                  • Test a non-empty string to be lowercase. Matching both alphabetical & numbers.

                                                  property nonBlank

                                                  readonly nonBlank: StringPredicate;
                                                  • Test a string to contain at least 1 non-whitespace character.

                                                  property nonEmpty

                                                  readonly nonEmpty: StringPredicate;
                                                  • Test a string to be not empty.

                                                  property numeric

                                                  readonly numeric: StringPredicate;
                                                  • Test a string to be numeric.

                                                  property uppercase

                                                  readonly uppercase: StringPredicate;
                                                  • Test a non-empty string to be uppercase. Matching both alphabetical & numbers.

                                                  property url

                                                  readonly url: StringPredicate;
                                                  • Test a string to be a valid URL.

                                                  method endsWith

                                                  endsWith: (searchString: string) => this;
                                                  • Test a string to end with a specific value.

                                                    Parameter searchString

                                                    The value that should be the end of the string.

                                                  method equals

                                                  equals: <S extends string>(expected: S) => Predicate<S>;
                                                  • Test a string to be equal to a specified string.

                                                    Parameter expected

                                                    Expected value to match.

                                                  method includes

                                                  includes: (searchString: string) => this;
                                                  • Test a string to include a specific value.

                                                    Parameter searchString

                                                    The value that should be included in the string.

                                                  method length

                                                  length: (length: number) => this;
                                                  • Test a string to have a specific length.

                                                    Parameter length

                                                    The length of the string.

                                                  method matches

                                                  matches: (regex: RegExp) => this;
                                                  • Test a string against a regular expression.

                                                    Parameter regex

                                                    The regular expression to match the value with.

                                                  method maxLength

                                                  maxLength: (length: number) => this;
                                                  • Test a string to have a maximum length.

                                                    Parameter length

                                                    The maximum length of the string.

                                                  method minLength

                                                  minLength: (length: number) => this;
                                                  • Test a string to have a minimum length.

                                                    Parameter length

                                                    The minimum length of the string.

                                                  method oneOf

                                                  oneOf: <S extends readonly string[]>(list: S) => Predicate<S[number]>;
                                                  • Test if the string is an element of the provided list.

                                                    Parameter list

                                                    List of possible values.

                                                  method startsWith

                                                  startsWith: (searchString: string) => this;
                                                  • Test a string to start with a specific value.

                                                    Parameter searchString

                                                    The value that should be the start of the string.

                                                  class TypedArrayPredicate

                                                  class TypedArrayPredicate<T extends TypedArray> extends Predicate<T> {}

                                                    constructor

                                                    constructor(
                                                    type: string,
                                                    options?: PredicateOptions,
                                                    validators?: Validator<T>[]
                                                    );

                                                    method byteLength

                                                    byteLength: (byteLength: number) => this;
                                                    • Test a typed array to have a specific byte length.

                                                      Parameter byteLength

                                                      The byte length of the typed array.

                                                    method length

                                                    length: (length: number) => this;
                                                    • Test a typed array to have a specific length.

                                                      Parameter length

                                                      The length of the typed array.

                                                    method maxByteLength

                                                    maxByteLength: (byteLength: number) => this;
                                                    • Test a typed array to have a minimum byte length.

                                                      Parameter length

                                                      The minimum byte length of the typed array.

                                                    method maxLength

                                                    maxLength: (length: number) => this;
                                                    • Test a typed array to have a maximum length.

                                                      Parameter length

                                                      The maximum length of the typed array.

                                                    method minByteLength

                                                    minByteLength: (byteLength: number) => this;
                                                    • Test a typed array to have a minimum byte length.

                                                      Parameter byteLength

                                                      The minimum byte length of the typed array.

                                                    method minLength

                                                    minLength: (length: number) => this;
                                                    • Test a typed array to have a minimum length.

                                                      Parameter length

                                                      The minimum length of the typed array.

                                                    method withValidators

                                                    protected withValidators: (validators: Array<Validator<T>>) => this;

                                                    class WeakMapPredicate

                                                    class WeakMapPredicate<KeyType extends object = object> extends Predicate<
                                                    WeakMap<KeyType, unknown>
                                                    > {}

                                                      constructor

                                                      constructor(
                                                      options?: PredicateOptions,
                                                      validators?: Validator<WeakMap<KeyType, unknown>>[]
                                                      );

                                                      method hasAnyKeys

                                                      hasAnyKeys: (...keys: readonly KeyType[]) => this;
                                                      • Test a WeakMap to include any of the provided keys. The keys are tested by identity, not structure.

                                                        Parameter keys

                                                        The keys that could be a key in the WeakMap.

                                                      method hasKeys

                                                      hasKeys: (...keys: readonly KeyType[]) => this;
                                                      • Test a WeakMap to include all the provided keys. The keys are tested by identity, not structure.

                                                        Parameter keys

                                                        The keys that should be a key in the WeakMap.

                                                      class WeakSetPredicate

                                                      class WeakSetPredicate<T extends object = object> extends Predicate<WeakSet<T>> {}

                                                        constructor

                                                        constructor(options?: PredicateOptions, validators?: Validator<WeakSet<T>>[]);

                                                        method has

                                                        has: (...items: readonly T[]) => this;
                                                        • Test a WeakSet to include all the provided items. The items are tested by identity, not structure.

                                                          Parameter items

                                                          The items that should be a item in the WeakSet.

                                                        method hasAny

                                                        hasAny: (...items: readonly T[]) => this;
                                                        • Test a WeakSet to include any of the provided items. The items are tested by identity, not structure.

                                                          Parameter items

                                                          The items that could be a item in the WeakSet.

                                                        Type Aliases

                                                        type AssertingValidator

                                                        type AssertingValidator<T> = T extends ReusableValidator<infer R>
                                                        ? (value: unknown, label?: string) => asserts value is R
                                                        : T extends BasePredicate<infer R>
                                                        ? (value: unknown, label?: string) => asserts value is R
                                                        : never;
                                                        • Turn a ReusableValidator into one with a type assertion.

                                                          Example 1

                                                          const checkUsername = ow.create(ow.string.minLength(3));
                                                          const checkUsername_: AssertingValidator<typeof checkUsername> = checkUsername;

                                                          Example 2

                                                          const predicate = ow.string.minLength(3);
                                                          const checkUsername: AssertingValidator<typeof predicate> = ow.create(predicate);

                                                        type BasePredicate

                                                        type BasePredicate<T = unknown> = {
                                                        [optionalSymbol]?: boolean;
                                                        [nullableSymbol]?: boolean;
                                                        [absentSymbol]?: boolean;
                                                        [testSymbol](
                                                        value: T,
                                                        main: Main,
                                                        label: string | Function,
                                                        idLabel?: boolean
                                                        ): void;
                                                        };

                                                        type Infer

                                                        type Infer<P> = P extends BasePredicate<infer T> ? T : never;
                                                        • Retrieve the type from the given predicate.

                                                          Example 1

                                                          import ow, {Infer} from 'ow';
                                                          const userPredicate = ow.object.exactShape({
                                                          name: ow.string
                                                          });
                                                          type User = Infer<typeof userPredicate>;

                                                        type Main

                                                        type Main = <T>(
                                                        value: T,
                                                        label: string | Function,
                                                        predicate: BasePredicate<T>,
                                                        idLabel?: boolean
                                                        ) => void;

                                                        type Ow

                                                        type Ow = {
                                                        /**
                                                        Test if the value matches the predicate. Throws an `ArgumentError` if the test fails.
                                                        @param value - Value to test.
                                                        @param predicate - Predicate to test against.
                                                        */
                                                        <T>(value: unknown, predicate: BasePredicate<T>): asserts value is T;
                                                        /**
                                                        Test if `value` matches the provided `predicate`. Throws an `ArgumentError` with the specified `label` if the test fails.
                                                        @param value - Value to test.
                                                        @param label - Label which should be used in error messages.
                                                        @param predicate - Predicate to test against.
                                                        */
                                                        <T>(
                                                        value: unknown,
                                                        label: string,
                                                        predicate: BasePredicate<T>
                                                        ): asserts value is T;
                                                        /**
                                                        Returns `true` if the value matches the predicate, otherwise returns `false`.
                                                        @param value - Value to test.
                                                        @param predicate - Predicate to test against.
                                                        */
                                                        isValid: <T>(value: unknown, predicate: BasePredicate<T>) => value is T;
                                                        /**
                                                        Validate a value against a predicate without throwing. Returns a result object with type narrowing.
                                                        @param value - Value to test.
                                                        @param predicate - Predicate to test against.
                                                        @returns A discriminated union: `{success: true; value: T}` or `{success: false; error: ArgumentError}`.
                                                        @example
                                                        ```
                                                        import ow from 'ow';
                                                        const result = ow.validate(value, ow.string);
                                                        if (!result.success) {
                                                        console.error(result.error.message);
                                                        return;
                                                        }
                                                        // result.value is now typed as string
                                                        console.log(result.value.length);
                                                        ```
                                                        */
                                                        validate: (<T>(
                                                        value: unknown,
                                                        predicate: BasePredicate<T>
                                                        ) => ValidateResult<T>) &
                                                        (<T>(
                                                        value: unknown,
                                                        label: string,
                                                        predicate: BasePredicate<T>
                                                        ) => ValidateResult<T>);
                                                        /**
                                                        Test if the provided value is an Ow predicate.
                                                        Useful for building higher-order functions that need to distinguish between predicates and other values.
                                                        @param value - Value to test.
                                                        @returns `true` if the value is an Ow predicate, `false` otherwise.
                                                        */
                                                        isPredicate: (value: unknown) => value is BasePredicate;
                                                        /**
                                                        Create a reusable validator.
                                                        @param predicate - Predicate used in the validator function.
                                                        @example
                                                        ```
                                                        import ow, {type ReusableValidator} from 'ow';
                                                        // Explicit type annotation required for type narrowing
                                                        const checkUsername: ReusableValidator<string> = ow.create(ow.string.minLength(3));
                                                        checkUsername('foo');
                                                        //=> throws ArgumentError
                                                        ```
                                                        */
                                                        create: (<T>(predicate: BasePredicate<T>) => ReusableValidator<T>) &
                                                        (<T>(label: string, predicate: BasePredicate<T>) => ReusableValidator<T>);
                                                        } & Modifiers &
                                                        Predicates;

                                                          type PredicateOptions

                                                          type PredicateOptions = {
                                                          optional?: boolean;
                                                          nullable?: boolean;
                                                          absent?: boolean;
                                                          };

                                                          type Predicates

                                                          type Predicates = {
                                                          /**
                                                          Test the value to be a string.
                                                          */
                                                          readonly string: StringPredicate;
                                                          /**
                                                          Test the value to be a number.
                                                          */
                                                          readonly number: NumberPredicate;
                                                          /**
                                                          Test the value to be an bigint.
                                                          */
                                                          readonly bigint: BigIntPredicate;
                                                          /**
                                                          Test the value to be a boolean.
                                                          */
                                                          readonly boolean: BooleanPredicate;
                                                          /**
                                                          Test the value to be undefined.
                                                          */
                                                          readonly undefined: Predicate<undefined>;
                                                          /**
                                                          Test the value to be null.
                                                          */
                                                          readonly null: Predicate<null>;
                                                          /**
                                                          Test the value to be null or undefined.
                                                          */
                                                          readonly nullOrUndefined: Predicate<null | undefined>;
                                                          /**
                                                          Test the value to be not a number.
                                                          */
                                                          readonly nan: Predicate<number>;
                                                          /**
                                                          Test the value to be a Symbol.
                                                          */
                                                          readonly symbol: Predicate<symbol>;
                                                          /**
                                                          Test the value to be an array.
                                                          */
                                                          readonly array: ArrayPredicate;
                                                          /**
                                                          Test the value to be an object.
                                                          */
                                                          readonly object: ObjectPredicate;
                                                          /**
                                                          Test the value to be a Date.
                                                          */
                                                          readonly date: DatePredicate;
                                                          /**
                                                          Test the value to be an Error.
                                                          */
                                                          readonly error: ErrorPredicate;
                                                          /**
                                                          Test the value to be a Map.
                                                          */
                                                          readonly map: MapPredicate;
                                                          /**
                                                          Test the value to be a WeakMap.
                                                          */
                                                          readonly weakMap: WeakMapPredicate;
                                                          /**
                                                          Test the value to be a Set.
                                                          */
                                                          readonly set: SetPredicate;
                                                          /**
                                                          Test the value to be a WeakSet.
                                                          */
                                                          readonly weakSet: WeakSetPredicate;
                                                          /**
                                                          Test the value to be a Function.
                                                          */
                                                          readonly function: Predicate<Function>;
                                                          /**
                                                          Test the value to be a RegExp.
                                                          */
                                                          readonly regExp: Predicate<RegExp>;
                                                          /**
                                                          Test the value to be a Promise.
                                                          */
                                                          readonly promise: Predicate<Promise<unknown>>;
                                                          /**
                                                          Test the value to be a typed array.
                                                          */
                                                          readonly typedArray: TypedArrayPredicate<TypedArray>;
                                                          /**
                                                          Test the value to be a Int8Array.
                                                          */
                                                          readonly int8Array: TypedArrayPredicate<Int8Array>;
                                                          /**
                                                          Test the value to be a Uint8Array.
                                                          */
                                                          readonly uint8Array: TypedArrayPredicate<Uint8Array>;
                                                          /**
                                                          Test the value to be a Uint8ClampedArray.
                                                          */
                                                          readonly uint8ClampedArray: TypedArrayPredicate<Uint8ClampedArray>;
                                                          /**
                                                          Test the value to be a Int16Array.
                                                          */
                                                          readonly int16Array: TypedArrayPredicate<Int16Array>;
                                                          /**
                                                          Test the value to be a Uint16Array.
                                                          */
                                                          readonly uint16Array: TypedArrayPredicate<Uint16Array>;
                                                          /**
                                                          Test the value to be a Int32Array.
                                                          */
                                                          readonly int32Array: TypedArrayPredicate<Int32Array>;
                                                          /**
                                                          Test the value to be a Uint32Array.
                                                          */
                                                          readonly uint32Array: TypedArrayPredicate<Uint32Array>;
                                                          /**
                                                          Test the value to be a Float32Array.
                                                          */
                                                          readonly float32Array: TypedArrayPredicate<Float32Array>;
                                                          /**
                                                          Test the value to be a Float64Array.
                                                          */
                                                          readonly float64Array: TypedArrayPredicate<Float64Array>;
                                                          /**
                                                          Test the value to be a ArrayBuffer.
                                                          */
                                                          readonly arrayBuffer: ArrayBufferPredicate<ArrayBuffer>;
                                                          /**
                                                          Test the value to be a SharedArrayBuffer.
                                                          */
                                                          readonly sharedArrayBuffer: ArrayBufferPredicate<SharedArrayBuffer>;
                                                          /**
                                                          Test the value to be a DataView.
                                                          */
                                                          readonly dataView: DataViewPredicate;
                                                          /**
                                                          Test the value to be Iterable.
                                                          */
                                                          readonly iterable: Predicate<Iterable<unknown>>;
                                                          /**
                                                          Test that the value matches at least one of the given predicates.
                                                          */
                                                          any: <T extends readonly BasePredicate[]>(
                                                          ...predicates: T
                                                          ) => AnyPredicate<
                                                          {
                                                          [K in keyof T]: T[K] extends BasePredicate<infer U> ? U : never;
                                                          }[number]
                                                          >;
                                                          };

                                                            type ReusableValidator

                                                            type ReusableValidator<T> = {
                                                            /**
                                                            Test if the value matches the predicate. Throws an `ArgumentError` if the test fails.
                                                            @param value - Value to test.
                                                            @param label - Override the label which should be used in error messages.
                                                            */
                                                            (value: unknown, label?: string): asserts value is T;
                                                            };
                                                            • A reusable validator.

                                                              Example 1

                                                              import ow, {type ReusableValidator} from 'ow';
                                                              // Explicit type annotation is required for type narrowing to work
                                                              const checkUsername: ReusableValidator<string> = ow.create(ow.string.minLength(3));
                                                              function setUsername(username: unknown) {
                                                              checkUsername(username);
                                                              // `username` is now typed as `string`
                                                              console.log(username.length);
                                                              }

                                                            type Shape

                                                            type Shape = {
                                                            [key: string]: BasePredicate | Shape;
                                                            };

                                                              type ValidateResult

                                                              type ValidateResult<T> =
                                                              | {
                                                              success: true;
                                                              value: T;
                                                              }
                                                              | {
                                                              success: false;
                                                              error: ArgumentError;
                                                              };
                                                              • Result of a validation that doesn't throw.

                                                                Example 1

                                                                import ow, {type ValidateResult} from 'ow';
                                                                const result: ValidateResult<string> = ow.validate(value, ow.string);
                                                                if (!result.success) {
                                                                console.error(result.error.message);
                                                                return;
                                                                }
                                                                // result.value is now typed as string
                                                                console.log(result.value.length);

                                                              type Validator

                                                              type Validator<T> = {
                                                              message(value: T, label?: string, result?: unknown): string;
                                                              validator(value: T): unknown;
                                                              /**
                                                              Provide custom message used by `not` operator.
                                                              When absent, the return value of `message()` is used and 'not' is inserted after the first 'to', e.g. `Expected 'smth' to be empty` -> `Expected 'smth' to not be empty`.
                                                              */
                                                              negatedMessage?(value: T, label: string): string;
                                                              };

                                                              Package Files (22)

                                                              Dependencies (6)

                                                              Dev Dependencies (11)

                                                              Peer Dependencies (0)

                                                              No peer dependencies.

                                                              Badge

                                                              To add a badge like this onejsDocs.io badgeto 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/ow.

                                                              • Markdown
                                                                [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/ow)
                                                              • HTML
                                                                <a href="https://www.jsdocs.io/package/ow"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>