fp-either-ref

Quick reference for Either type. Use when user needs error handling, validation, or operations that can fail with typed errors.

31,392 stars
Complexity: easy

About this skill

The `fp-either-ref` skill equips an AI agent with a structured quick reference guide for the `Either` type from the `fp-ts` library. This functional programming construct is crucial for explicit and type-safe error handling and validation in TypeScript applications. The skill covers fundamental concepts such as creating `Right` (success) and `Left` (failure) values, transforming them using `map` and `mapLeft`, and chaining operations with `flatMap`. By providing clear examples for common patterns like `fromNullable` and `tryCatch`, it empowers the agent to assist developers in writing more predictable, maintainable, and error-resilient code, promoting a functional approach to managing potential failures.

Best use case

An AI agent can use this skill to: - Generate TypeScript code snippets that effectively handle errors using the `fp-ts/Either` pattern. - Explain the principles and benefits of functional error handling to developers. - Provide guidance on validating inputs, processing API responses, or managing operations that can fail gracefully. - Debug or refactor existing code to incorporate `Either` for improved error transparency.

Quick reference for Either type. Use when user needs error handling, validation, or operations that can fail with typed errors.

Upon utilizing this skill, the AI agent will be able to: - Provide accurate and concise explanations of the `Either` type and its utility. - Generate correct and idiomatic `fp-ts/Either` code examples tailored to the user's scenario. - Guide the user through the process of implementing functional error handling and validation. - Facilitate a deeper understanding of functional programming concepts related to error management.

Practical example

Example input

Show me how to use `fp-ts/Either` to handle potential errors when fetching data from an API and then transforming it.

Example output

```typescript
import * as E from 'fp-ts/Either';
import { pipe } from 'fp-ts/function';

interface User { id: number; name: string; }

// Simulate an API call that might fail
const fetchData = (id: number): E.Either<Error, string> => {
  if (id < 0) {
    return E.left(new Error('Invalid user ID'));
  }
  return E.right(`{"id":${id}, "name":"User ${id}"}`);
};

// Simulate parsing data, which might also fail
const parseData = (jsonString: string): E.Either<Error, User> => {
  try {
    const data = JSON.parse(jsonString);
    if (typeof data.id !== 'number' || typeof data.name !== 'string') {
      return E.left(new Error('Invalid data structure'));
    }
    return E.right(data);
  } catch (e: any) {
    return E.left(new Error(`Parsing error: ${e.message}`));
  }
};

// Example usage:
const getUser = (id: number): E.Either<Error, User> => {
  return pipe(
    fetchData(id), // Returns Either<Error, string>
    E.flatMap(parseData), // Chained operation: if fetchData is Right, parseData runs
    E.mapLeft(err => new Error(`Operation failed: ${err.message}`)) // Transform the error type if needed
  );
};

// Successful scenario
pipe(
  getUser(1),
  E.fold(
    (error) => console.error('Failed to get user:', error.message),
    (user) => console.log('Successfully got user:', user.name)
  )
); // Output: Successfully got user: User 1

// Failure scenario (invalid ID)
pipe(
  getUser(-1),
  E.fold(
    (error) => console.error('Failed to get user:', error.message),
    (user) => console.log('Successfully got user:', user.name)
  )
); // Output: Failed to get user: Operation failed: Invalid user ID

// Failure scenario (parsing error due to bad data format - conceptual for demonstration)
const getCorruptUser = (id: number): E.Either<Error, User> => {
    return pipe(
      E.right(`THIS IS NOT JSON`),
      E.flatMap(parseData)
    );
};
pipe(
  getCorruptUser(2),
  E.fold(
    (error) => console.error('Failed to get corrupt user:', error.message),
    (user) => console.log('Successfully got corrupt user:', user.name)
  )
); // Output: Failed to get corrupt user: Parsing error: Unexpected token 'T', "THIS IS NOT J" is not valid JSON
```

When to use this skill

  • Utilize this skill when a user: - Asks for best practices in error handling or validation within a TypeScript project, particularly with a functional programming emphasis. - Inquires about the `fp-ts` library, the `Either` type, or concepts like `Left` and `Right`. - Needs assistance in converting imperative error handling (e.g., exceptions, null checks) to a functional, `Either`-based approach. - Requests code examples for common `Either` operations (e.g., mapping, flatMapping, error transformation).

When not to use this skill

  • Avoid using this skill when: - The task involves error handling in languages other than TypeScript, or frameworks that do not benefit from `fp-ts`. - The user's query is about basic, non-functional error handling mechanisms (e.g., standard `try/catch` without `Either` encapsulation). - The operation does not inherently involve potential failure or complex validation logic. - The context is entirely outside of software development or functional programming paradigms.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/fp-either-ref/SKILL.md --create-dirs "https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/main/plugins/antigravity-awesome-skills-claude/skills/fp-either-ref/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/fp-either-ref/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How fp-either-ref Compares

Feature / Agentfp-either-refStandard Approach
Platform SupportClaudeLimited / Varies
Context Awareness High Baseline
Installation ComplexityeasyN/A

Frequently Asked Questions

What does this skill do?

Quick reference for Either type. Use when user needs error handling, validation, or operations that can fail with typed errors.

Which AI agents support this skill?

This skill is designed for Claude.

How difficult is it to install?

The installation complexity is rated as easy. You can find the installation instructions above.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Either Quick Reference

Either = success or failure. `Right(value)` or `Left(error)`.

## When to Use

- You need a quick fp-ts reference for typed synchronous error handling.
- The task involves validation, fallible operations, or converting throwing code to `Either`.
- You want a compact cheat sheet rather than a long tutorial.

## Create

```typescript
import * as E from 'fp-ts/Either'

E.right(value)           // Success
E.left(error)            // Failure
E.fromNullable(err)(x)   // null → Left(err), else Right(x)
E.tryCatch(fn, toError)  // try/catch → Either
```

## Transform

```typescript
E.map(fn)                // Transform Right value
E.mapLeft(fn)            // Transform Left error
E.flatMap(fn)            // Chain (fn returns Either)
E.filterOrElse(pred, toErr) // Right → Left if pred fails
```

## Extract

```typescript
E.getOrElse(err => default)  // Get Right or default
E.match(onLeft, onRight)     // Pattern match
E.toUnion(either)            // E | A (loses type info)
```

## Common Patterns

```typescript
import { pipe } from 'fp-ts/function'
import * as E from 'fp-ts/Either'

// Validation
const validateEmail = (s: string): E.Either<string, string> =>
  s.includes('@') ? E.right(s) : E.left('Invalid email')

// Chain validations (stops at first error)
pipe(
  E.right({ email: 'test@example.com', age: 25 }),
  E.flatMap(d => pipe(validateEmail(d.email), E.map(() => d))),
  E.flatMap(d => d.age >= 18 ? E.right(d) : E.left('Must be 18+'))
)

// Convert throwing code
const parseJson = (s: string) => E.tryCatch(
  () => JSON.parse(s),
  (e) => `Parse error: ${e}`
)
```

## vs try/catch

```typescript
// ❌ try/catch - errors not in types
try {
  const data = JSON.parse(input)
  process(data)
} catch (e) {
  handleError(e)
}

// ✅ Either - errors explicit in types
pipe(
  E.tryCatch(() => JSON.parse(input), String),
  E.map(process),
  E.match(handleError, identity)
)
```

Use Either when **error type matters** and you want to chain operations.

Related Skills

fp-taskeither-ref

31392
from sickn33/antigravity-awesome-skills

Quick reference for TaskEither. Use when user needs async error handling, API calls, or Promise-based operations that can fail.

Developer ToolsClaude

n8n-expression-syntax

31392
from sickn33/antigravity-awesome-skills

Validate n8n expression syntax and fix common errors. Use when writing n8n expressions, using {{}} syntax, accessing $json/$node variables, troubleshooting expression errors, or working with webhook data in workflows.

Developer ToolsClaude

mermaid-expert

31392
from sickn33/antigravity-awesome-skills

Create Mermaid diagrams for flowcharts, sequences, ERDs, and architectures. Masters syntax for all diagram types and styling.

Developer ToolsClaude

mcp-builder-ms

31392
from sickn33/antigravity-awesome-skills

Use this skill when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

Developer ToolsClaude

makepad-deployment

31392
from sickn33/antigravity-awesome-skills

CRITICAL: Use for Makepad packaging and deployment. Triggers on: deploy, package, APK, IPA, 打包, 部署, cargo-packager, cargo-makepad, WASM, Android, iOS, distribution, installer, .deb, .dmg, .nsis, GitHub Actions, CI, action, marketplace

Developer ToolsClaude

macos-menubar-tuist-app

31392
from sickn33/antigravity-awesome-skills

Build, refactor, or review SwiftUI macOS menubar apps that use Tuist.

Developer ToolsClaude

kaizen

31392
from sickn33/antigravity-awesome-skills

Guide for continuous improvement, error proofing, and standardization. Use this skill when the user wants to improve code quality, refactor, or discuss process improvements.

Developer ToolsClaude

issues

31392
from sickn33/antigravity-awesome-skills

Interact with GitHub issues - create, list, and view issues.

Developer ToolsClaude

hugging-face-tool-builder

31392
from sickn33/antigravity-awesome-skills

Your purpose is now is to create reusable command line scripts and utilities for using the Hugging Face API, allowing chaining, piping and intermediate processing where helpful. You can access the API directly, as well as use the hf command line tool.

Developer ToolsClaude

git-pushing

31392
from sickn33/antigravity-awesome-skills

Stage all changes, create a conventional commit, and push to the remote branch. Use when explicitly asks to push changes ("push this", "commit and push"), mentions saving work to remote ("save to github", "push to remote"), or completes a feature and wants to share it.

Developer ToolsClaude

git-hooks-automation

31392
from sickn33/antigravity-awesome-skills

Master Git hooks setup with Husky, lint-staged, pre-commit framework, and commitlint. Automate code quality gates, formatting, linting, and commit message enforcement before code reaches CI.

Developer ToolsClaude

gh-review-requests

31392
from sickn33/antigravity-awesome-skills

Fetch unread GitHub notifications for open PRs where review is requested from a specified team or opened by a team member. Use when asked to "find PRs I need to review", "show my review requests", "what needs my review", "fetch GitHub review requests", or "check team review queue".

Developer ToolsClaude