Created
February 4, 2025 13:09
-
-
Save shmurakami/38f2561da5405ace0a3c863028728442 to your computer and use it in GitHub Desktop.
typescript match, result, option
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Err, err, Ok, ok, type Result } from "neverthrow"; | |
import { none, Option, some } from "ts-option"; | |
import { match, P } from "ts-pattern"; | |
type Foo = { | |
str: string; | |
some: Option<string>; | |
none: Option<string>; | |
}; | |
const make = (val: boolean): Result<Foo, Error> => { | |
if (val) { | |
return ok({ | |
str: "hello", | |
some: some("foo"), | |
none: none, | |
}); | |
} else { | |
return err(new Error("failed")); | |
} | |
}; | |
const okRes = make(true); | |
const errRes = make(false); | |
match(okRes) | |
.with(P.instanceOf(Ok), (foo) => console.log("ok!", foo)) | |
.with(P.instanceOf(Err), (err) => console.error("error...", err)) | |
.exhaustive(); | |
match(errRes) | |
.with(P.instanceOf(Ok), (foo) => console.log("ok!", foo)) | |
.with(P.instanceOf(Err), (err) => console.error("error...", err)) | |
.exhaustive(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment