Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 49 lines · 2.2 KiB · at 83c2f03

// v2 in plain .ts: Option is T | undefined, Result a plain tagged object, match a typed function.// Checked by `tsus check --v2`, bundled by esbuild unchanged, run by node.import { Err, Ok, html, match, matchLiteral, matchResult, sql, untrusted, validate, type Option, type Result } from "@tsus/v2";type Shape =  | { readonly kind: "circle"; readonly r: number }  | { readonly kind: "rect"; readonly w: number; readonly h: number };const area = (s: Shape): number =>  match(s, "kind", {    circle: (c) => Math.round(Math.PI * c.r * c.r),    rect: (r) => r.w * r.h,  });type Method = "GET" | "POST";const verb = (m: Method): string => matchLiteral(m, { GET: () => "read", POST: () => "write" });// Option: an index read is Option<T> under noUncheckedIndexedAccess; === undefined narrows it.const first = <T,>(xs: readonly T[]): Option<T> => xs[0];const port = (raw: Option<string>): number => {  const n = raw === undefined ? Number.NaN : Number(raw);  return Number.isInteger(n) ? n : 8080;};type ParseError = { readonly kind: "empty" } | { readonly kind: "not_a_number"; readonly text: string };const parse = (s: string): Result<number, ParseError> => {  if (s === "") return Err({ kind: "empty" });  const n = Number(s);  return Number.isNaN(n) ? Err({ kind: "not_a_number", text: s }) : Ok(n);};const describe = (s: string): string =>  matchResult(parse(s), {    ok: (n) => `number ${n}`,    err: (e) => match(e, "kind", { empty: () => "empty", not_a_number: (x) => `not a number: ${x.text}` }),  });const q = sql`SELECT id FROM issues WHERE repo_id = ${"r1"} AND title LIKE ${"%bug%"} ORDER BY ${sql.ident("number")}`;const title = untrusted("<b>hi</b>");const slug = validate(untrusted("my-repo"), /[a-z-]+/);console.log(area({ kind: "circle", r: 2 }), area({ kind: "rect", w: 3, h: 4 }));console.log(verb("GET"), verb("POST"));console.log(first(["hello", "world"]) ?? "none", first<string>([]) ?? "none");console.log(port("0"), port(undefined), port("x"));console.log(describe("42"), "|", describe(""), "|", describe("4x"));console.log(q.text);console.log(JSON.stringify(q.params));console.log(html`<p>${title}</p>`.html);console.log(slug ?? "invalid", validate(untrusted("../etc"), /[a-z-]+/) ?? "invalid");