Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Text · 52 lines · 1.4 KiB · at f30ac63

import { Ok, Err, type Result } from "@tsus/runtime";type Method = "GET" | "POST" | "DELETE";// Literal arms that cover a finite union need no _ arm.const verb = (m: Method): string =>  match (m) {    "GET" => "read",    "POST" => "write",    "DELETE" => "remove",  };const sign = (n: -1 | 0 | 1): string =>  match (n) {    -1 => "negative",    0 => "zero",    1 => "positive",  };const toggle = (on: boolean): string =>  match (on) {    true => "on",    false => "off",  };// A plain number is not finite, so it needs _.const status = (code: number): string =>  match (code) {    200 => "ok",    404 => "missing",    _ => "other",  };// The declared return type flows into every arm, so the raw object literals// below are checked against HttpError instead of widening to { kind: string }.type HttpError = { kind: "not_found" } | { kind: "teapot"; code: number };const fetchStatus = (code: number): Result<string, HttpError> =>  match (code) {    404 => Err({ kind: "not_found" }),    418 => Err({ kind: "teapot", code }),    _ => Ok("fine"),  };const explain = (r: Result<string, HttpError>): string =>  match (r) {    Ok(body) => body,    Err(e) => e.kind,  };console.log(verb("POST"), sign(-1), toggle(false), status(404), status(500));console.log(explain(fetchStatus(200)), explain(fetchStatus(404)), explain(fetchStatus(418)));