mcpField
F
fp-ts Option and Either

fp-ts Option and Either

github.com/whatiskadudoing開発1450 回インストール39 週間前に更新
リポジトリ

fp-ts Option and Either について

TypeScript 開発者向けに、fp-ts の Option と Either で欠損値やエラーを表す方法を解説するガイドです。合成、検証、安全なアクセスの例を扱います。

主な機能

  1. 01Option と Either の使い分け
  2. 02nullable 値の処理
  3. 03値の合成と変換
  4. 04例外を Either に変換
  5. 05Either によるデータ検証
  6. 06配列とレコードの安全な参照

活用シーン

  1. 01API やオブジェクトの任意フィールドの表現
  2. 02try-catch を使わない失敗処理
  3. 03合成可能な検証パイプラインの構築

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/whatiskadudoing/fp-ts-skills --skill fp-ts-option-and-either

インストール後、Claude Code で/fp-ts-option-and-eitherを入力して読み込まれたか確認します。

詳細

fp-ts の Option と Either ガイド

このスキルでは、より安全な TypeScript コードを書くための fp-ts の Option と Either の実践的な使い方を説明します。

Option と Either の使い分け

Option を使う場合:
  • 値が存在する場合と存在しない場合があるとき(null または undefined の可能性がある場合)
  • 値が存在しない理由を知る必要がないとき
  • オプションのフィールド、配列の検索、辞書へのアクセスを扱うとき
Either を使う場合:
  • 操作が失敗する可能性があり、エラー情報が必要なとき
  • try-catch ブロックを置き換えるとき
  • 失敗の理由を複数の種類に分けて伝える必要があるとき
  • バリデーションパイプラインを構築するとき

インポート

// Option imports
import * as O from 'fp-ts/Option'
import { pipe } from 'fp-ts/function'

// Either imports
import * as E from 'fp-ts/Either'
import { pipe } from 'fp-ts/function'

// Both together
import * as O from 'fp-ts/Option'
import * as E from 'fp-ts/Either'
import { pipe, flow } from 'fp-ts/function'

Option:null 許容値の処理

null 許容値を Option に変換する
import * as O from 'fp-ts/Option'
import { pipe } from 'fp-ts/function'

// fromNullable: converts null/undefined to None, otherwise Some
const maybeUser = O.fromNullable(getUserById(id)) // Option<User>

// fromPredicate: creates Some if predicate passes, None otherwise
const positiveNumber = O.fromPredicate((n: number) => n > 0)(value)

// Manual construction
const some = O.some(42)        // Some(42)
const none = O.none            // None
Option から値を取り出す
// getOrElse: provide a default value
const username = pipe(
  maybeUser,
  O.map(user => user.name),
  O.getOrElse(() => 'Anonymous')
)

// getOrElseW: wider type for default (when types differ)
const result = pipe(
  maybeNumber,
  O.getOrElseW(() => 'not found' as const)
) // number | 'not found'

// fold/match: handle both cases explicitly
const greeting = pipe(
  maybeUser,
  O.fold(
    () => 'Hello, stranger!',           // None case
    (user) => `Hello, ${user.name}!`    // Some case
  )
)

// Alternative: match (same as fold, more descriptive name)
const greeting = pipe(
  maybeUser,
  O.match(
    () => 'Hello, stranger!',
    (user) => `Hello, ${user.name}!`
  )
)
Option の値を変換する
// map: transform the inner value (if present)
const userName = pipe(
  maybeUser,
  O.map(user => user.name)
) // Option<string>

// chain (flatMap): when transformation returns Option
const userEmail = pipe(
  maybeUser,
  O.chain(user => O.fromNullable(user.email))
) // Option<string>

// filter: keep Some only if predicate passes
const adultUser = pipe(
  maybeUser,
  O.filter(user => user.age >= 18)
)
Option を組み合わせる
// sequenceArray: convert Option<T>[] to Option<T[]>
import { sequenceArray } from 'fp-ts/Option'

const maybeNumbers: O.Option<number>[] = [O.some(1), O.some(2), O.some(3)]
const allNumbers = sequenceArray(maybeNumbers) // Some([1, 2, 3])

const withNone: O.Option<number>[] = [O.some(1), O.none, O.some(3)]
const result = sequenceArray(withNone) // None

// ap: apply Option<(a: A) => B> to Option<A>
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))
) // Some(3)

Either:エラーの処理

try-catch を Either に変換する
import * as E from 'fp-ts/Either'
import { pipe } from 'fp-ts/function'

// tryCatch: wraps throwing functions
const parseJSON = (json: string): E.Either<Error, unknown> =>
  E.tryCatch(
    () => JSON.parse(json),
    (error) => error instanceof Error ? error : new Error(String(error))
  )

// Usage
const result = parseJSON('{"valid": "json"}') // Right({ valid: 'json' })
const error = parseJSON('invalid json')        // Left(SyntaxError)

// tryCatchK: creates a function that returns Either
const safeParseJSON = E.tryCatchK(
  JSON.parse,
  (error) => error instanceof Error ? error : new Error(String(error))
)
Either の値を作成する
// Manual construction
const success = E.right(42)                    // Right(42)
const failure = E.left('Something went wrong') // Left('Something went wrong')

// fromNullable: convert nullable to Either with error
const getUser = (id: string): E.Either<string, User> =>
  pipe(
    findUserById(id),
    E.fromNullable(`User not found: ${id}`)
  )

// fromPredicate: create Right if predicate passes
const validateAge = E.fromPredicate(
  (age: number) => age >= 18,
  (age) => `Age ${age} is below minimum of 18`
)
Either から値を取り出す
// fold/match: handle both cases
const message = pipe(
  result,
  E.fold(
    (error) => `Error: ${error.message}`,  // Left case
    (data) => `Success: ${JSON.stringify(data)}` // Right case
  )
)

// getOrElse: provide default for Left case
const value = pipe(
  result,
  E.getOrElse((error) => defaultValue)
)

// getOrElseW: wider type for default
const value = pipe(
  result,
  E.getOrElseW((error) => null)
) // T | null
Either の値を変換する
// map: transform Right value
const userAge = pipe(
  getUser(id),
  E.map(user => user.age)
) // Either<string, number>

// mapLeft: transform Left value (error mapping)
const withBetterError = pipe(
  result,
  E.mapLeft(error => new CustomError(error.message))
)

// bimap: transform both sides
const formatted = pipe(
  result,
  E.bimap(
    (error) => `Error: ${error}`,
    (value) => `Value: ${value}`
  )
)

// chain (flatMap): when transformation returns Either
const userProfile = pipe(
  getUser(id),
  E.chain(user => getProfile(user.profileId))
) // Either<string, Profile>

// chainW: chain with wider error type
const result = pipe(
  validateEmail(input),      // Either<ValidationError, string>
  E.chainW(sendEmail)        // Either<NetworkError, Response>
) // Either<ValidationError | NetworkError, Response>
バリデーションパターン
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' })

// Sequential validation (stops at first error)
const validateUser = (email: string, password: string) =>
  pipe(
    E.Do,
    E.bind('email', () => validateEmail(email)),
    E.bind('password', () => validatePassword(password))
  )

// For collecting all errors, use Validation from fp-ts
import * as A from 'fp-ts/Apply'
import { getSemigroup } from 'fp-ts/NonEmptyArray'

const applicativeValidation = E.getApplicativeValidation(
  getSemigroup<ValidationError>()
)

よく使われるパターン

安全な配列アクセス
import * as A from 'fp-ts/Array'
import * as O from 'fp-ts/Option'

// head: safely get first element
const first = A.head([1, 2, 3]) // Some(1)
const empty = A.head([])        // None

// lookup: safely get element by index
const second = A.lookup(1)([1, 2, 3]) // Some(2)
const outOfBounds = A.lookup(10)([1, 2, 3]) // None
安全なオブジェクトプロパティへのアクセス
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)    // Some('localhost')
const missing = R.lookup('port')(config) // None
Option と Either の相互変換
import * as O from 'fp-ts/Option'
import * as E from 'fp-ts/Either'

// Option to Either
const toEither = O.toEither(() => 'Value was missing')
const either = pipe(maybeValue, toEither) // Either<string, T>

// Either to Option (discards error)
const toOption = E.toOption
const option = pipe(either, toOption) // Option<T>
TaskEither を使った非同期操作
import * as TE from 'fp-ts/TaskEither'
import { pipe } from 'fp-ts/function'

// Wrap async operations
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))
  )

// Chain async operations
const getUserProfile = (id: string) =>
  pipe(
    fetchUser(id),
    TE.chain(user => fetchProfile(user.profileId)),
    TE.map(profile => profile.displayName)
  )

// Execute
const result = await getUserProfile('123')() // Either<Error, string>

ベストプラクティス

  1. 合成しやすく、ツリーシェイキングの効果も得られるため、メソッドチェーンより pipe を優先してください

  2. システム境界で fromNullable を使い、外部から受け取った null 許容値を変換してください

  3. Either では一般的な文字列ではなく、具体的なエラー型を使ってください

  4. 型推論を活用し、TypeScript が推論できる場合は明示的な型注釈を避けてください

  5. エラー型が異なる場合は chainW を使い、共用体型を自動的に拡張してください

  6. 最後に値を取り出す際は fold/match を優先し、両方のケースを確実に処理してください

避けるべきアンチパターン

制御フローに isSome/isRight を使わない
// BAD: loses type narrowing benefits
if (O.isSome(maybeUser)) {
  console.log(maybeUser.value.name)
}

// GOOD: use fold/match
pipe(
  maybeUser,
  O.fold(
    () => console.log('No user'),
    (user) => console.log(user.name)
  )
)
Option/Either をネストしない
// BAD: creates Option<Option<T>>
const nested = pipe(
  maybeUser,
  O.map(user => O.fromNullable(user.email))
) // Option<Option<string>>

// GOOD: use chain to flatten
const flat = pipe(
  maybeUser,
  O.chain(user => O.fromNullable(user.email))
) // Option<string>
getOrElse を早い段階で使わない
// BAD: extracts value too early, loses composition
const name = pipe(maybeUser, O.getOrElse(() => defaultUser)).name

// GOOD: keep in Option context, extract at the end
const name = pipe(
  maybeUser,
  O.map(user => user.name),
  O.getOrElse(() => 'Unknown')
)
Left の値を無視しない
// BAD: silently discards error information
const value = pipe(result, E.getOrElse(() => defaultValue))

// GOOD: handle or log errors appropriately
const value = pipe(
  result,
  E.fold(
    (error) => {
      logger.error('Operation failed', error)
      return defaultValue
    },
    (value) => value
  )
)
パラダイムを混在させない
// BAD: mixing try-catch with Either
try {
  const result = pipe(
    parseJSON(input),
    E.chain(validate)
  )
} catch (e) {
  // This defeats the purpose
}

// GOOD: stay in Either world
pipe(
  parseJSON(input),
  E.chain(validate),
  E.fold(
    (error) => handleError(error),
    (value) => handleSuccess(value)
  )
)

コメント