typescript+matchtypescriptmatch
match consumer examples
How a TypeScript app uses @danrabydev/match ^0.3.1: exhaustive Status.match, one ApiResult namespace, peek-then-match, merge, and diagnostics on Error. No _ hatch.
typescriptapp/src/page.ts
import { type TagMismatch } from "@danrabydev/match";
import {
ApiResult,
getPost,
getUser,
interceptErrors,
type ApiError,
} from "./api.js";
function isTagMismatch(err: unknown): err is TagMismatch {
return (
typeof err === "object" &&
err !== null &&
"reason" in err &&
err.reason === "tag-mismatch"
);
}
export function loadPage(userId: string, postId: string) {
return ApiResult.merge(getUser(userId), getPost(postId));
}
export function handlePage(result: ReturnType<typeof loadPage>): string {
ApiResult.peek(result, interceptErrors);
return ApiResult.match(result, {
Idle: () => "idle",
Loading: ({ msg }) => msg.join(", "),
Success: ({ data: [user, post] }) => `${user.name}: ${post.title}`,
Error: ({ err }) => {
if (isTagMismatch(err)) return `mismatch: ${err.tags.join(",")}`;
const [first] = err as ApiError[];
if (first === undefined) return "error";
return `${first.code}: ${first.message}`;
},
Cached: ({ at }) => at[0]?.toISOString() ?? "",
});
}
handlePage(loadPage("1", "9"));
// => "ada: notes"