KrustyKrab: Rust-Inspired Utilities for JavaScript/TypeScript

1.1.0 · active · verified Sun Apr 19

KrustyKrab provides idiomatic implementations of Rust's `Option` and `Result` types, along with several utility functions inspired by Rust's standard library, for JavaScript and TypeScript projects. It aims to enhance error handling and null safety by introducing concepts like explicit handling of present/absent values and success/failure states. The current stable version is 1.1.0. As a relatively new library focused on bringing Rust paradigms to TypeScript, its release cadence is likely driven by feature additions and improvements rather than a fixed schedule. Key differentiators include its faithful adaptation of `Option` and `Result` with methods like `unwrap`, `unwrapOr`, `map`, and `andThen`, as well as practical utilities such as `getResult` for converting Promises, `toOption` for nullable conversions, and `tryCatch` for wrapping synchronous operations in `Result` types. This approach encourages more robust, explicit, and functional error management compared to traditional try-catch blocks and null checks.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core `Option` and `Result` types, along with key utilities like `unwrap`, `getResult`, and `tryCatch`, showcasing their usage for null safety and robust error handling in TypeScript.

import { Some, None, Ok, Err, unwrap, getResult, toOption, tryCatch } from 'krustykrab';

// Demonstrating Option type for null safety
const maybeValue = Some("Hello, KrustyKrab!");
console.log(maybeValue.isSome()); // true
console.log(maybeValue.unwrapOr("Default")); // "Hello, KrustyKrab!"

const noValue = None<string>();
console.log(noValue.isNone()); // true
console.log(noValue.unwrapOr("Default Value")); // "Default Value"

// Demonstrating Result type for error handling
const successfulResult = Ok(42);
console.log(successfulResult.isOk()); // true
console.log(successfulResult.unwrap()); // 42

const failedResult = Err("Something went wrong!");
console.log(failedResult.isErr()); // true
console.log(failedResult.unwrapErr()); // "Something went wrong!"

// Utility: unwrap - panics on null/undefined
const fooOrNull: string | null = 'foo';
const guaranteedFoo = unwrap(fooOrNull); // 'foo'
// unwrap(null); // This would throw an error at runtime

// Utility: getResult - converting Promises
async function fetchData() {
  const dataPromise = Promise.resolve({ id: 1, name: 'Spongebob' });
  const result = await getResult(dataPromise);
  if (result.isOk()) {
    console.log('Fetched data:', result.unwrap());
  } else {
    console.error('Failed to fetch:', result.unwrapErr());
  }
}
fetchData();

// Utility: tryCatch - wrapping synchronous operations
const jsonString = '{"item":"crabby patty"}';
const parsedResult = tryCatch(() => JSON.parse(jsonString));
if (parsedResult.isOk()) {
  console.log('Parsed JSON:', parsedResult.unwrap());
} else {
  console.error('JSON parse error:', parsedResult.unwrapErr());
}

const invalidJsonString = '{invalid json}';
const invalidParsedResult = tryCatch(() => JSON.parse(invalidJsonString));
console.log('Invalid JSON parse was an error:', invalidParsedResult.isErr()); // true

view raw JSON →