Aller au contenu principal

safe()

safe<TArgs, TReturn>(fn): (...args) => Result<TReturn, Error>

Wraps a function to return a Result instead of throwing errors.


Type Parameters

TArgs: TArgs extends unknown[]

The argument types.

TReturn: TReturn

The return type.


Parameters

fn: (...args) => TReturn

The function to wrap.


Returns

A new function that returns a Result<TReturn, Error>.


Since

2.0.0


Example

import { chunk } from './chunk';

const safeChunk = safe(chunk);
const result = safeChunk([1, 2, 3, 4, 5], -1);

if (result.isOk()) {
console.log(result.value); // Array of chunks
} else {
console.log(result.error.message); // "Chunk size must be strictly positive"
}