跳到主要内容
哒哒星球DADA PLANET

Skill · 已公开版本

fp-either-ref · fp-ts Either 类型速查参考

提供 fp-ts 2.x 中 Either 的创建、变换、提取与链式校验代码片段,帮助实现类型化同步错误处理。

先看看示例

作者提供的示例,实际效果取决于你的输入和使用工具。

输入

把一段用 try/catch 解析 JSON 的代码改写为使用 E.tryCatch 与 E.match 的 Either 链式写法。

输出

预期交付:Either 相关函数用法与示例代码,含链式校验和 tryCatch 转换。(编辑说明,非实际运行结果)

方法说明

---
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.
risk: none
source: community
date_added: "2026-03-06"
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)`.

## 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 => fallbackValue)  // Get Right or default
E.match(onLeft, onRight)     // Pattern match
E.toUnion(either)            // E | A (loses type info)
```

## Common Patterns

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

// Toy validation; an @ check is not complete email 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.flatMap(data => E.tryCatch(() => process(data), String)),
  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.

## Reference scope

These are fp-ts 2.x fragments. Supply application variables, types, validators and imports, and check the installed version. `map` does not catch thrown exceptions. `Task` has no typed error channel; an improperly wrapped promise can still reject. Use `tryCatch` at fallible boundaries.

Official API: [fp-ts modules](https://gcanti.github.io/fp-ts/modules/).