JSPM

@vikiboss/to

1.0.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • 0
  • Score
    100M100P100Q9387F
  • License MIT

A TypeScript utility for elegant error handling

Package Exports

  • @vikiboss/to
  • @vikiboss/to/dist/index.js
  • @vikiboss/to/dist/index.mjs

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@vikiboss/to) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

@vikiboss/to

An elegant TypeScript error handling utility library.

Features

  • 🎯 Type Safety: Full TypeScript type support
  • 🚀 Lightweight: Zero dependencies
  • ⚡️ Dual Support: Handles both synchronous and asynchronous operations
  • 📦 Module Ready: Compatible with ESM and CommonJS

Installation

npm install @vikiboss/to

Usage

import { to } from '@vikiboss/to';

// Synchronous usage
const [ok, error, value] = to(() => {
  return "hello world";
});

if (ok) {
  console.log(value); // value is typed as string
} else {
  console.error(error);
}

// Asynchronous usage
const [ok, error, value] = await to(async () => {
  const response = await fetch('https://api.example.com');
  return response.json();
});

if (ok) {
  console.log(value); // value inherits the return type from API
} else {
  console.error(error);
}

API

to

type ToResult<T> =
  | readonly [ok: true, error: undefined, value: T]
  | readonly [ok: false, error: unknown, value: undefined]

/**
 * Safely executes a synchronous or asynchronous function, returning a result tuple.
 *
 * @param fn - Function to execute (sync or Promise-returning)
 * @returns Tuple containing:
 *          - ok: Execution status (boolean)
 *          - error: Captured error (undefined if successful)
 *          - value: Result value (undefined if failed)
 * 
 * For synchronous functions: Immediate result tuple
 * For async functions: Promise resolving to result tuple
 */
export function to<T>(fn: () => never): ToResult<never>
export function to<T>(fn: () => Promise<T>): Promise<ToResult<T>>
export function to<T>(fn: () => T): ToResult<T>
Return Value

A tuple containing three elements:

  • ok: Boolean indicating operation success
  • error: unknown | undefined error object (present when ok is false)
  • value: T | undefined result value (present when ok is true)

License

MIT