
关于
Either 类型快速参考。适用于用户需要错误处理、验证或可能以类型化错误失败的操作。
name: fp-either-ref description: Either 类型快速参考。当用户需要错误处理、验证或可能失败并带有类型化错误的操作时使用。 risk: unknown source: community version: 1.0.0 tags: [fp-ts, either, error-handling, validation, quick-reference]
Either 快速参考
Either = 成功或失败。Right(value) 或 Left(error)。
何时使用
- 你需要 fp-ts 类型化同步错误处理的快速参考。
- 任务涉及验证、可失败操作或将抛出异常的代码转换为
Either。 - 你想要一个紧凑的速查表而非长篇教程。
创建
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
转换
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
提取
E.getOrElse(err => default) // Get Right or default
E.match(onLeft, onRight) // Pattern match
E.toUnion(either) // E | A (loses type info)
常见模式
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}`
)
对比 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)
)
当错误类型很重要且你想链式操作时使用 Either。
限制
- 仅在任务明确匹配上述范围时使用此技能。
- 不要将输出视为环境特定验证、测试或专家审查的替代品。
- 如果缺少所需的输入、权限、安全边界或成功标准,请停下来寻求澄清。
兼容工具
Claude CodeCursor
标签
前端开发