Skip to content
← Retour au catalogue
Développementmoyencommunity

fp-either-ref

Référence rapide pour le type Either. Utilisez quand l'utilisateur a besoin de gestion d'erreurs, de validation ou d'opérations qui peuvent échouer avec des erreurs typées.

Le contenu de ce skill est dans sa langue d’origine (souvent l’anglais).

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

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

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

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

Common Patterns

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

// ❌ 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.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
— Field Manual

Les 1 441 skills, démystifiés en un PDF.

Un guide éditorial gratuit que nous avons écrit pour le Skills Atlas : taxonomie, les 25 skills indispensables, anti-patterns, parcours d’apprentissage par profil.

  • 70+ pages, sommaire, prêt à imprimer.
  • Envoyé par email — lien valide 7 jours.
  • Désabonnement en un clic à tout moment.

Pas de spam. Email jamais partagé. Désabonnement en un clic.