| name | fp-ts Option and Either |
| description | Functional error handling and nullable value management using fp-ts Option and Either types |
| version | 1.0.0 |
| author | kadu |
| tags | ["fp-ts","functional-programming","typescript","error-handling","option","either","monads"] |
fp-ts Option and Either Guide
This skill covers practical usage of Option and Either from fp-ts for safer TypeScript code.
When to Use Option vs Either
Use Option when:
- A value may or may not exist (nullable/undefined scenarios)
- You don't need to know WHY a value is missing
- Working with optional fields, array lookups, or dictionary access
Use Either when:
- An operation can fail and you need error information
- Replacing try-catch blocks
- You need to communicate different failure reasons
- Building validation pipelines
Imports
import * as O from 'fp-ts/Option'
import { pipe } from 'fp-ts/function'
import * as E from 'fp-ts/Either'
import { pipe } from 'fp-ts/function'
import * as O from 'fp-ts/Option'
import * as E from 'fp-ts/Either'
import { pipe, flow } from 'fp-ts/function'
Option: Handling Nullable Values
Converting Nullable Values to Option
import * as O from 'fp-ts/Option'
import { pipe } from 'fp-ts/function'
const maybeUser = O.fromNullable(getUserById(id))
const positiveNumber = O.fromPredicate((n: number) => n > 0)(value)
const some = O.some(42)
const none = O.none
Extracting Values from Option
const username = pipe(
maybeUser,
O.map(user => user.name),
O.getOrElse(() => 'Anonymous')
)
const result = pipe(
maybeNumber,
O.getOrElseW(() => 'not found' as const)
)
const greeting = pipe(
maybeUser,
O.fold(
() => 'Hello, stranger!',
(user) => `Hello, ${user.name}!`
)
)
const greeting = pipe(
maybeUser,
O.match(
() => 'Hello, stranger!',
(user) => `Hello, ${user.name}!`
)
)
Transforming Option Values
const userName = pipe(
maybeUser,
O.map(user => user.name)
)
const userEmail = pipe(
maybeUser,
O.chain(user => O.fromNullable(user.email))
)
const adultUser = pipe(
maybeUser,
O.filter(user => user.age >= 18)
)
Combining Options
import { sequenceArray } from 'fp-ts/Option'
const maybeNumbers: O.Option<number>[] = [O.some(1), O.some(2), O.some(3)]
const allNumbers = sequenceArray(maybeNumbers)
const withNone: O.Option<number>[] = [O.some(1), O.none, O.some(3)]
const result = sequenceArray(withNone)
import { ap } from 'fp-ts/Option'
const add = (a: number) => (b: number) => a + b
const result = pipe(
O.some(add),
ap(O.some(1)),
ap(O.some(2))
)
Either: Handling Errors
Converting Try-Catch to Either
import * as E from 'fp-ts/Either'
import { pipe } from 'fp-ts/function'
const parseJSON = (json: string): E.Either<Error, unknown> =>
E.tryCatch(
() => JSON.parse(json),
(error) => error instanceof Error ? error : new Error(String(error))
)
const result = parseJSON('{"valid": "json"}')
const error = parseJSON('invalid json')
const safeParseJSON = E.tryCatchK(
JSON.parse,
(error) => error instanceof Error ? error : new Error(String(error))
)
Creating Either Values
const success = E.right(42)
const failure = E.left('Something went wrong')
const getUser = (id: string): E.Either<string, User> =>
pipe(
findUserById(id),
E.fromNullable(`User not found: ${id}`)
)
const validateAge = E.fromPredicate(
(age: number) => age >= 18,
(age) => `Age ${age} is below minimum of 18`
)
Extracting Values from Either
const message = pipe(
result,
E.fold(
(error) => `Error: ${error.message}`,
(data) => `Success: ${JSON.stringify(data)}`
)
)
const value = pipe(
result,
E.getOrElse((error) => defaultValue)
)
const value = pipe(
result,
E.getOrElseW((error) => null)
)
Transforming Either Values
const userAge = pipe(
getUser(id),
E.map(user => user.age)
)
const withBetterError = pipe(
result,
E.mapLeft(error => new CustomError(error.message))
)
const formatted = pipe(
result,
E.bimap(
(error) => `Error: ${error}`,
(value) => `Value: ${value}`
)
)
const userProfile = pipe(
getUser(id),
E.chain(user => getProfile(user.profileId))
)
const result = pipe(
validateEmail(input),
E.chainW(sendEmail)
)
Validation Pattern
import * as E from 'fp-ts/Either'
import { pipe } from 'fp-ts/function'
type ValidationError = { field: string; message: string }
const validateEmail = (email: string): E.Either<ValidationError, string> =>
email.includes('@')
? E.right(email)
: E.left({ field: 'email', message: 'Invalid email format' })
const validatePassword = (password: string): E.Either<ValidationError, string> =>
password.length >= 8
? E.right(password)
: E.left({ field: 'password', message: 'Password too short' })
const validateUser = (email: string, password: string) =>
pipe(
E.Do,
E.bind('email', () => validateEmail(email)),
E.bind('password', () => validatePassword(password))
)
import * as A from 'fp-ts/Apply'
import { getSemigroup } from 'fp-ts/NonEmptyArray'
const applicativeValidation = E.getApplicativeValidation(
getSemigroup<ValidationError>()
)
Common Patterns
Safe Array Access
import * as A from 'fp-ts/Array'
import * as O from 'fp-ts/Option'
const first = A.head([1, 2, 3])
const empty = A.head([])
const second = A.lookup(1)([1, 2, 3])
const outOfBounds = A.lookup(10)([1, 2, 3])
Safe Object Property Access
import * as R from 'fp-ts/Record'
import * as O from 'fp-ts/Option'
const config: Record<string, string> = { host: 'localhost' }
const host = R.lookup('host')(config)
const missing = R.lookup('port')(config)
Converting Between Option and Either
import * as O from 'fp-ts/Option'
import * as E from 'fp-ts/Either'
const toEither = O.toEither(() => 'Value was missing')
const either = pipe(maybeValue, toEither)
const toOption = E.toOption
const option = pipe(either, toOption)
Async Operations with TaskEither
import * as TE from 'fp-ts/TaskEither'
import { pipe } from 'fp-ts/function'
const fetchUser = (id: string): TE.TaskEither<Error, User> =>
TE.tryCatch(
() => fetch(`/api/users/${id}`).then(r => r.json()),
(error) => error instanceof Error ? error : new Error(String(error))
)
const getUserProfile = (id: string) =>
pipe(
fetchUser(id),
TE.chain(user => fetchProfile(user.profileId)),
TE.map(profile => profile.displayName)
)
const result = await getUserProfile('123')()
Best Practices
-
Prefer pipe over method chaining for better composition and tree-shaking
-
Use fromNullable at system boundaries to convert external nullable values
-
Use descriptive error types with Either instead of generic strings
-
Leverage type inference - avoid explicit type annotations when TypeScript can infer
-
Use chainW when error types differ to automatically widen the union
-
Prefer fold/match for final extraction to ensure both cases are handled
Anti-Patterns to Avoid
Don't Use isSome/isRight for Control Flow
if (O.isSome(maybeUser)) {
console.log(maybeUser.value.name)
}
pipe(
maybeUser,
O.fold(
() => console.log('No user'),
(user) => console.log(user.name)
)
)
Don't Nest Options/Eithers
const nested = pipe(
maybeUser,
O.map(user => O.fromNullable(user.email))
)
const flat = pipe(
maybeUser,
O.chain(user => O.fromNullable(user.email))
)
Don't Use getOrElse Too Early
const name = pipe(maybeUser, O.getOrElse(() => defaultUser)).name
const name = pipe(
maybeUser,
O.map(user => user.name),
O.getOrElse(() => 'Unknown')
)
Don't Ignore Left Values
const value = pipe(result, E.getOrElse(() => defaultValue))
const value = pipe(
result,
E.fold(
(error) => {
logger.error('Operation failed', error)
return defaultValue
},
(value) => value
)
)
Don't Mix Paradigms
try {
const result = pipe(
parseJSON(input),
E.chain(validate)
)
} catch (e) {
}
pipe(
parseJSON(input),
E.chain(validate),
E.fold(
(error) => handleError(error),
(value) => handleSuccess(value)
)
)