Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 97 lines · 5.2 KiB · at 9472e3c

# TypeScript-Ultra-Strict (tsus) primerThis is the language reference the eval harness gives the model for the `.tsus` side. It describes the compiler as it exists in this repository (`packages/cli`, `packages/runtime`), not the full proposal. If the compiler changes (typed `match`, a `?` operator), update this file in the same commit so the primer never teaches a language the checker does not implement.## What a .tsus file isA `.tsus` file is TypeScript with five things removed and one macro added. It compiles to plain ESM JavaScript.Removed, each with a stable diagnostic code:| Code | Banned | Use instead ||---|---|---|| TSUS001 | `class` declarations and expressions | plain object types and functions || TSUS002 | `null` | `Option<T>` (`Some(v)` / `None`) || TSUS003 | the identifier `undefined` | `Option<T>`; `fromNullable` at the boundary || TSUS004 | `var` | `const` (preferred) or `let` || TSUS005 | `throw` | return `Result<T, E>` (`Ok(v)` / `Err(e)`) |Also do not use optional properties (`x?: T`), optional parameters, or optional chaining (`a?.b`). They produce `undefined` at runtime, which defeats the point. Model absence as an `Option<T>` field instead. The one exception is describing the shape of external data (parsed JSON, a `.ts` dependency) right before you convert it with `fromNullable`.## The runtime```tsimport { Some, None, Ok, Err, tag, type Option, type Result, type Tagged } from "@tsus/runtime";import { fromNullable, wrapSync, wrapAsync } from "@tsus/runtime/boundary";````Option<T>` methods: `isSome()`, `isNone()`, `map(f)`, `andThen(f)` (f returns an Option), `unwrapOr(fallback)`, `okOr(error)` (to a Result).`Result<T, E>` methods: `isOk()`, `isErr()`, `map(f)`, `mapErr(f)`, `andThen(f)` (f returns a Result), `unwrapOr(fallback)`, `ok()` (to an Option).There is no `unwrap()`. To get a value out, use `match` or `unwrapOr`.Constructors: `Some(v)`, `None` (a value, not a function), `Ok(v)`, `Err(e)`, and `tag("Name", payload)` for tagged unions (`Tagged<"Name", Payload>` is `{ tag: "Name"; value: Payload }`).## The match macro```tsconst label = match (findUser(id)) {  Some(user) => user.name,  None => "anonymous",};const message = match (parsePort(raw)) {  Ok(port) => `listening on ${port}`,  Err(e) => `bad port: ${e.kind}`,};```Rules:- Patterns: `Some(x)`, `None`, `Ok(x)`, `Err(e)`, any tag of a `Tagged` union (`Circle(c)` binds the payload), string or number literals (`"GET" => ...`, `404 => ...`), and the wildcard `_`.- Each arm body is a single expression. Do not write `Pattern(x) => { statements }`; braces are parsed as an object literal. When an arm needs several steps, call a helper function, or use a ternary.- Arms are tried top to bottom. A match with no matching arm crashes at runtime (`TSUS100`), so cover every variant or end with `_`.- If an arm body uses `await`, the whole match becomes a promise: write `await match (x) { ... }`.- `match` only fires as `match (expr) {`. A method call like `str.match(/re/)` is untouched.You do not have to use `match`; `if (opt.isSome())` plus `unwrapOr` or `map` is fine too. Use whatever is clearest.## The boundary: talking to JavaScript APIsBuilt-in and npm APIs still return `undefined`/`null` and still throw. Convert at the edge:- Nullable values: `fromNullable(map.get(key))`, `fromNullable(arr.find(p))`, `fromNullable(arr[i])` for an index that may be out of range, `fromNullable(obj[key])` for data from JSON, `fromNullable(str.match(re))`.- Throwing calls: `wrapSync(JSON.parse)(text)` returns `Result<any, Error>`; likewise `wrapSync(decodeURIComponent)(s)`. `wrapAsync(fn)` does the same for async functions and returns `Promise<Result<...>>`.- Values typed `unknown` (parsed JSON, request bodies): check with `typeof`, `Array.isArray`, `Number.isInteger`, and `fromNullable` for missing keys. `typeof v === "undefined"` is a string comparison and is allowed, but `fromNullable(v).isNone()` reads better.Inside the boundary, everything you write returns `Option` or `Result`, never `undefined` and never an exception.## A complete example```tsimport { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime";import { fromNullable, wrapSync } from "@tsus/runtime/boundary";export type User = { id: string; email: Option<string> };export type LoadError = { kind: "invalid_json" } | { kind: "not_found"; id: string };const parseUsers = (raw: string): Result<User[], LoadError> =>  wrapSync(JSON.parse)(raw)    .mapErr((): LoadError => ({ kind: "invalid_json" }))    .map((data: Array<{ id: string; email?: string }>) =>      data.map((u) => ({ id: u.id, email: fromNullable(u.email) })),    );export const emailFor = (raw: string, id: string): Result<Option<string>, LoadError> =>  parseUsers(raw).andThen((users) =>    match (fromNullable(users.find((u) => u.id === id))) {      Some(user) => Ok(user.email),      None => Err({ kind: "not_found", id }),    },  );```## Checker status`tsus check` enforces the five bans and the macro syntax. At the time this primer was written it did not yet run full semantic type-checking, so type errors in a `.tsus` file show up when the hidden tests run rather than at compile time. Write well-typed code anyway.