Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 7.0 KiB · at 2cc04ee

Writing TypeScript-Ultra-Strict (.tsus)

This project uses .tsus files: TypeScript with the escape hatches removed. Plain .ts files keep working and are not checked. Everything below applies to .tsus only. Read it once before writing code; tsus explain <CODE> covers any single rule in depth.

The loop

  1. Write or edit .tsus files under src/.
  2. Run tsus check --json. Each diagnostic has a stable code, a position, a hint, and usually a fix with exact text edits.
  3. Run tsus fix to apply every safe fix (--unsafe adds fixes that can change behavior; review those). Or apply a diagnostic's fix.edits yourself: each edit replaces [start, end) (UTF-16 offsets into the original file) with newText.
  4. For anything left, run tsus explain <CODE> and change the code. Do not work around a rule: there is no suppression comment, and as, any and ! are themselves errors.
  5. Repeat until tsus check passes, then tsus build emits plain ESM into dist/.

To port a .ts file, run tsus migrate src/file.ts. It writes src/file.tsus next to it and lists what it could not convert.

What is not allowed

No null, no undefined, no class, no var, no throw, no any, no as casts (except as const), no ! non-null assertions, no enum, no == or !=, no default exports, no @ts-ignore/@ts-expect-error/@ts-nocheck. Do not reassign or mutate function parameters. Use const unless the binding really is reassigned. Every promise is awaited or returned. Every Result is matched, propagated or returned. Result error types are string literal unions or tagged unions.

Types

TypeScript
import { Some, None, Ok, Err, tag, type Option, type Result, type Tagged } from "@tsus/runtime";

type User = { readonly name: string; readonly email: Option<string> }; // data is plain objects

const ada: User = { name: "ada", email: Some("ada@example.com") };
const nobody: Option<string> = None;

// Errors are a closed set the caller can match on.
type LoadError = "empty id" | Tagged<"NotFound", string> | { tag: "Timeout"; ms: number };

const load = (id: string): Result<User, LoadError> =>
  id === "" ? Err("empty id") : Err(tag("NotFound", id));
  • Option<T>: Some(value) or None. Methods: map, andThen, unwrapOr(fallback), okOr(error), isSome(), isNone().
  • Result<T, E>: Ok(value) or Err(error). Methods: map, mapErr, andThen, unwrapOr(fallback), ok(), isOk(), isErr().
  • Tagged<"Name", V> and tag("Name", value) build tagged variants; any object type with a literal tag field works too.
  • Behavior lives in functions that take data and return new data: const rename = (u: User, name: string): User => ({ ...u, name });.
  • A void operation that can fail returns Result<true, E> and ends with return Ok(true);.

match

match is a macro and an expression. Each arm is Pattern => expression, separated by commas.

TypeScript
const greet = (u: User): string =>
  match (u.email) {
    Some(address) => `mail ${address}`,
    None => `no email for ${u.name}`,
  };

const explain = (e: LoadError): string =>
  match (e) {
    "empty id" => "no id given",        // literal pattern
    NotFound(id) => `no user ${id}`,     // Tagged variant: binds its value
    _ => "timed out",                     // wildcard
  };
  • Patterns: Some(x), None, Ok(x), Err(e), any tag name Variant(x) (binds .value for Tagged, the whole object otherwise), string or number literals, and _.
  • Arms are expressions, not blocks. Put multi-step logic in a named function and call it from the arm.
  • Matches nest. An arm may await; then write await match (...) { ... }.

The ? operator

? after a Result or Option expression returns early with its Err or None, and otherwise yields the inner value. It only works inside a function whose declared return type is a Result or Option (or a Promise of one), and the error types must line up (use mapErr first if not). In async code, await first: const user = (await load(id))?;.

TypeScript
const total = (rawA: string, rawB: string): Result<number, ParseError> => {
  const a = parse(rawA)?;
  const b = parse(rawB)?;
  return Ok(a + b);
};

The boundary

The outside world (npm, DOM, Node, .ts files) returns undefined, throws, and hands you classes. Convert it at the edge:

TypeScript
import { tag, type Tagged } from "@tsus/runtime";
import { fromNullable, wrapSync, wrapAsync } from "@tsus/runtime/boundary";
import { readFile } from "node:fs/promises";

const first = fromNullable([1, 2].find((n) => n > 1)); // T | null | undefined -> Option<T>
const parseJson = wrapSync(JSON.parse);                 // throws -> Result<T, Error>
const read = wrapAsync(readFile);                       // rejects -> Promise<Result<T, Error>>

type ReadError = Tagged<"ReadFailed", string>;
const text = (await read("a.txt", "utf8")).mapErr((e): ReadError => tag("ReadFailed", e.message));

Map Error into your own tagged error type right away with mapErr. A file named *.boundary.tsus may use as casts (after a runtime check) and default exports (for hosts such as Cloudflare Workers that require export default). All other rules still apply there. Keep boundary files small; validate untrusted data with a schema library such as zod and return a Result.

Diagnostic codes

Code Rule Fix
TSUS000 Syntax error none
TSUS001 Classes are banned none
TSUS002 null is banned none
TSUS003 undefined is banned none
TSUS004 var is banned safe
TSUS005 throw is banned none
TSUS006 Malformed match expression none
TSUS100 Non-exhaustive match (runtime) none
TSUS401 any is banned safe
TSUS402 as casts are banned outside boundary files none
TSUS403 Non-null assertions are banned none
TSUS404 enum is banned unsafe
TSUS405 == and != are banned safe
TSUS406 Default exports are banned outside boundary files unsafe
TSUS407 Reassigning a parameter is banned none
TSUS408 let that is never reassigned safe
TSUS409 Mutating a parameter is banned unsafe
TSUS410 Result error types must be tagged none
TSUS411 Floating promises are banned unsafe
TSUS412 Unused Result none
TSUS413 Type-check suppressions are banned safe

tsus explain <CODE> prints the rule, why it exists, a rejected and an accepted example. tsus check --json diagnostics look like:

JSON
{ "code": "TSUS405", "message": "loose equality (== / !=) is banned in .tsus files", "hint": "Use === or !==.",
  "file": "src/main.tsus", "line": 3, "col": 48, "endLine": 3, "endCol": 50, "start": 97, "end": 99,
  "explain": "tsus explain TSUS405",
  "fix": { "description": "Replace == with ===", "safe": true,
           "edits": [{ "start": 97, "end": 99, "line": 3, "col": 48, "endLine": 3, "endCol": 50, "newText": "===" }] } }

fix is null when no automatic fix exists. Safe fixes keep runtime behavior (they can surface type errors that any was hiding); unsafe ones ("safe": false) can change it.