| name | fp-either-ref |
| description | Quick reference for Either type. Use when user needs error handling, validation, or operations that can fail with typed errors. |
| version | 1.0.0 |
| tags | ["fp-ts","either","error-handling","validation","quick-reference"] |
Either Quick Reference
Either = success or failure. Right(value) or Left(error).
Create
import * as E from 'fp-ts/Either'
E.right(value)
E.left(error)
E.fromNullable(err)(x)
E.tryCatch(fn, toError)
Transform
E.map(fn)
E.mapLeft(fn)
E.flatMap(fn)
E.filterOrElse(pred, toErr)
Extract
E.getOrElse(err => default)
E.match(onLeft, onRight)
E.toUnion(either)
Common Patterns
import { pipe } from 'fp-ts/function'
import * as E from 'fp-ts/Either'
const validateEmail = (s: string): E.Either<string, string> =>
s.includes('@') ? E.right(s) : E.left('Invalid email')
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+'))
)
const parseJson = (s: string) => E.tryCatch(
() => JSON.parse(s),
(e) => `Parse error: ${e}`
)
vs try/catch
try {
const data = JSON.parse(input)
process(data)
} catch (e) {
handleError(e)
}
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.