NeverThrow
類似
Result
と ResultAsync
に関する便利関数を提供するlibrary
method chainで Result
型を扱える
返り値がplane objectじゃないから、RSCからRCCに対して返せないな

method chainでResult型を扱える
fp-tsよりも範囲狭いし、簡単そうで良さそう
fp-tsよりもtypescriptからの逸脱さが小さい気がする
monadシラン人でも直感的に扱えそう
fp-tsはpipeだったり、doだったりある
同じようなコードを書いて比較してみるか
try/catchを Result
に変換する
tsimport { Result } from "neverthrow";
type ParseError = { message: string };
const toParseError = (): ParseError => ({ message: "Parse Error" });
const safeJsonParse = Result.fromThrowable(JSON.parse, toParseError);
const res = safeJsonParse("{");
使用例
tsimport { 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>
Result.combineWithAllErrors (static class method)
Asynchronous API (ResultAsync)
Promise<Result<T,E>>
で済むことが多い

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)
Utilities
fromThrowable
fromPromise
fromSafePromise
Testing
A note on the Package Name