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"
}