Home Reference Source Test
import {Predicate} from 'tiny-types/lib/predicates/Predicate'
public class | source

Predicate

Direct Subclass:

src/predicates/Predicate.ts~SingleConditionPredicate

Describes a Condition that the value should meet.

To define a custom predicate to be used with the check function you can either extend the Predicate, or use the Predicate.to factory method.

Example:

Assuming we'd like to create an isDefined() predicate:
ensure(`some value`, value, isDefined());
We can either use the Predicate.to factory method:

import { Predicate } from 'tiny-types';

function isDefined<T>(): Predicate<T> {
    return Predicate.to(`be defined`, (value: T) =>
        ! (value === null || value === undefined),
    );
}
or extend the Predicate itself

import { Predicate, Result, Success, Failure } from 'tiny-types';

function isDefined<T>() {
  return new IsDefined<T>();
}

class IsDefined<T> extends Predicate<T> {
    check(value: T): Result<T> {
      return ! (value === null || value === undefined)
        ? new Success(value)
        : new Failure(value, `be defined`);
    }
}

Static Method Summary

Static Public Methods
public static

to(description: string, condition: Condition<V>): Predicate<V>

A factory method instantiating a single-condition predicate.

Static Public Methods

public static to(description: string, condition: Condition<V>): Predicate<V> source

A factory method instantiating a single-condition predicate. You can use it instead of extending the {Predicate} to save some keystrokes.

Params:

NameTypeAttributeDescription
description string

The description of the condition is used by check to generate the error message. The description should be similar tobe defined, be less than some value for the error message to make sense.

condition Condition<V>

a function that takes a value of type V and returns a boolean indicating whether or not the condition is met. For example: (value: V) => !! value

Return:

Predicate<V>

Example:

Predicate.to(`be defined`, (value: T) => ! (value === null || value === undefined));