Skip to content

Instantly share code, notes, and snippets.

@shmurakami
Created February 4, 2025 13:09
Show Gist options
  • Save shmurakami/38f2561da5405ace0a3c863028728442 to your computer and use it in GitHub Desktop.
Save shmurakami/38f2561da5405ace0a3c863028728442 to your computer and use it in GitHub Desktop.
typescript match, result, option
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