NeverThrow
github
wiki
類似
fp-ts
option-t
ts-belt
https://github.com/mobily/ts-belt
oxide.ts
https://github.com/traverse1984/oxide.ts
monads
#WIP
ResultとResultAsyncに関する便利関数を提供するlibrary
method chainでResult型を扱える
返り値がplane objectじゃないから、RSCからRCCに対して返せないなmrsekut.icon
Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported.になる
method chainでResult型を扱える
fp-tsよりも範囲狭いし、簡単そうで良さそう
fp-tsよりもtypescriptからの逸脱さが小さい気がする
monadシラン人でも直感的に扱えそう
fp-tsはpipeだったり、doだったりある
https://gcanti.github.io/fp-ts/guides/do-notation.html
https://dev.classmethod.jp/articles/fp-ts-compsing-monad-by-pipe/
同じようなコードを書いて比較してみるか
try/catchをResultに変換する
code: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("{");
使用例
https://speakerdeck.com/naoya/typescript-niyoru-graphql-batukuendokai-fa?slide=48
code: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)
Result.mapErr()
Result.unwrapOr()
Okならその値を返し、Errなら引数のdefault値を返す
andThen
ref Eitherのbind
Result.asyncAndThen (method)
Result.orElse()
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.icon
okAsync
errAsync
ResultAsync.fromPromise (static class method)
https://github.com/supermacro/neverthrow/wiki/Working-with-ResultAsync
これなんで関数の色消えるんだ、
ResultAsync.fromSafePromise (static class method)
ResultAsync.map (method)
ResultAsync.mapErr (method)
ResultAsync.unwrapOr (method)
ResultAsync.andThen (method)
ResultAsync.orElse (method)
ResultAsync.match (method)
neverthrow: ResultAsync.combine
Promise.all()みたいなやつ
neverthrow: ResultAsync.combineWithAllErrors
Promise.allSettled()みたいなやつ
Utilities
fromThrowable
fromPromise
fromSafePromise
Testing
A note on the Package Name