generated at
NeverThrow


類似



Result ResultAsync に関する便利関数を提供するlibrary
method chainで Result 型を扱える

返り値がplane objectじゃないから、RSCからRCCに対して返せないなmrsekut



method chainでResult型を扱える
fp-tsよりも範囲狭いし、簡単そうで良さそう
fp-tsよりもtypescriptからの逸脱さが小さい気がする
monadシラン人でも直感的に扱えそう

fp-tsはpipeだったり、doだったりある

同じようなコードを書いて比較してみるか

try/catchを Result に変換する
ts
import { Result } from "neverthrow"; type ParseError = { message: string }; const toParseError = (): ParseError => ({ message: "Parse Error" }); const safeJsonParse = Result.fromThrowable(JSON.parse, toParseError); const res = safeJsonParse("{");



使用例
ts
import { Result, ok, err } from "neverthrow"; function itsUnder100(n: number): Result<number, Error> { return n <= 100 ? ok(n) : err(new Error("Number is over 100")); } function itsEven(n: number): Result<number, Error> { return n % 2 === 0 ? ok(n) : err(new Error("Number is odd")); } function itsPositive(n: number): Result<number, Error> { return n >= 0 ? ok(n) : err(new Error("Number is negative")); } const result = ok(96) .andThen(itsUnder100) .andThen(itsEven) .andThen(itsPositive); result.match( (n) => console.log(n), (e) => console.log(e.message) );
なんで new Error してる?



docsよみ
Recommended: Use eslint-plugin-neverthrow
Top-Level API
API Documentation
Synchronous API (Result)
ok, err
Result.isOk (method), Result.isErr (method)
Okならその値を返し、Errなら引数のdefault値を返す
andThen
Result.asyncAndThen (method)
Result.match (method)
Result.asyncMap (method)
Result.fromThrowable (static class method)
Result.combine (static class method)
function combine<T, E>(resultList: Result<T, E>[]): Result<T[], E>
traverse的なやつ
Result.combineWithAllErrors (static class method)
Asynchronous API (ResultAsync)
Promise<Result<T,E>> で済むことが多いmrsekut
okAsync
errAsync
ResultAsync.fromPromise (static class method)
これなんで関数の色消えるんだ、
ResultAsync.fromSafePromise (static class method)
ResultAsync.map (method)
ResultAsync.mapErr (method)
ResultAsync.unwrapOr (method)
ResultAsync.andThen (method)
ResultAsync.orElse (method)
ResultAsync.match (method)
Promise.all()みたいなやつ
Promise.allSettled()みたいなやつ
Utilities
fromThrowable
fromPromise
fromSafePromise
Testing
A note on the Package Name