Skip to content

Variable: validate()

readonly validate: {<T>(value, predicate): Result<T, Error>; <T, E>(value, predicate, onError): Result<T, E>; }

Defined in: core/factories.ts:339

Call Signature

<T>(value, predicate): Result<T, Error>

Creates a Result by validating a value with a predicate function.

If the predicate returns true, creates Ok with the value. If it returns false, creates Err with default or custom error.

Type Parameters

T

T

Value type

Parameters

value

T

Value to validate

predicate

(value) => boolean

Function that validates the value

Returns

Result<T, Error>

Ok if valid, Err with default error if invalid

Example

ts
// Simple validation
const age = Result.validate(25, (x) => x >= 18)
// Ok(25)

const invalid = Result.validate(15, (x) => x >= 18)
// Err(Error: Validation failed for value: 15)

Call Signature

<T, E>(value, predicate, onError): Result<T, E>

Creates a Result by validating a value with predicate and custom error.

Type Parameters

T

T

Value type

E

E

Error type

Parameters

value

T

Value to validate

predicate

(value) => boolean

Function that validates the value

onError

(value) => E

Function that generates custom error on rejection

Returns

Result<T, E>

Ok if valid, Err with custom error if invalid

Examples

ts
// With personalized error message
const age = Result.validate(
  15,
  (x) => x >= 18,
  () => new Error(`${x} years is underage`)
)
// Err(Error: 15 years is underage)
ts
// With custom error type
type ValidationError = { field: string; value: unknown; rule: string }
const result = Result.validate(
  -5,
  (x) => x > 0,
  (x) => ({ field: 'age', value: x, rule: 'must be positive' })
)