Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 8.7 KiB · at 8b87e58

TypeScript-Ultra-Strict (tsus) primer

This 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 (new syntax, new bans, different checking), update this file in the same commit so the primer never teaches a language the checker does not implement.

What a .tsus file is

A .tsus file is TypeScript with its escape hatches 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))
TSUS401 any unknown, then narrow
TSUS402 as casts (except as const) narrow with typeof/Array.isArray, or isRecord/asRecord/field from the boundary
TSUS403 non-null x! fromNullable(x) and match or unwrapOr
TSUS404 enum a union of string literals
TSUS405 == and != === and !==
TSUS406 default exports named exports
TSUS407 reassigning a parameter a new const
TSUS408 let that is never reassigned const
TSUS409 mutating a parameter (p.x = 1, p.push(x), map.set on a Map parameter, Object.assign(p, ...)) return a new value: { ...p, x }, [...xs, x], toSorted(); mutate only values the function created
TSUS410 a Result error type that is not a string literal union or a tagged union (Result<T, string>, Result<T, Error>) "not_found" | "timeout", or objects with a literal kind or tag field
TSUS411 a promise that is neither awaited nor returned (also void p and xs.forEach(async ...)) await it or return it
TSUS412 calling a function that returns a Result and ignoring it match on it or return it
TSUS413 @ts-ignore, @ts-expect-error, @ts-nocheck fix the code

tsus check --json diagnostics carry a hint and often a fix with exact text edits; tsus explain <CODE> prints the full rule.

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

TypeScript
import { Some, None, Ok, Err, tag, type Option, type Result, type Tagged } from "@tsus/runtime";
import { fromNullable, wrapSync, wrapAsync, isRecord, asRecord, field } 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

TypeScript
const 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: the value field if the variant has one, else error, else the whole variant), string, number, or boolean literals ("GET" => ..., 404 => ..., true => ...), and the wildcard _. Do not mix variant and literal patterns in one match.
  • 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.
  • The match is checked at compile time. Every variant needs an arm unless there is a _ arm (a missing one is TSUS201), an arm for a variant the type does not have is TSUS202, and each arm's binding is typed as that variant's payload. Literal arms over a finite union ("GET" | "POST") need no _ once every member is listed; over a plain string or number they always need _.
  • When the match has a declared type (a function return type, an annotated const), every arm is checked against it, so Err({ kind: "missing" }) gets the declared error type. Otherwise the match's type is the union of the arms.
  • If an arm body uses await, every arm becomes async and the match is 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 ? operator

Inside a function whose declared return type is Result<T, E>, Option<T>, or Promise of one, expr? unwraps an Ok/Some and returns an Err/None from the function early:

TypeScript
const loadPort = (raw: string): Result<number, ConfigError> => {
  const n = parseNumber(raw)?; // returns the Err if parsing failed
  return n > 0 ? Ok(n) : Err({ kind: "out_of_range", value: n });
};

const fetchName = async (id: string): Promise<Result<string, ApiError>> => {
  const user = await getUser(id)?; // ? applies to the awaited Result
  return Ok(user.name);
};
  • The error type must fit: an Err<string> cannot propagate out of a function returning Result<T, number>, and None can only propagate out of a function returning Option (TSUS302). Convert first with mapErr or okOr.
  • ? covers everything to its left, like the ?: operator. Inside a larger expression, parenthesize: Ok((a()?) + (b()?)).
  • Not allowed at top level, in a function without a declared Result/Option return type, or inside a match arm (TSUS300); not on a value that is not a Result/Option (TSUS301); not in a ?: branch, on the right of &&/||/??, or in a loop condition (TSUS303).

The boundary: talking to JavaScript APIs

Built-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. Since as casts are banned, use the boundary's narrowing helpers: isRecord(v) (a type guard for a plain object, not null, not an array), asRecord(v) (an Option<Record<string, unknown>>) and field(v, key) (an own property as an Option<unknown>). 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

TypeScript
import { 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 bans above and the macro syntax, then type-checks the whole file with TypeScript in strict mode. Type errors are reported at their .tsus line and column as TSUS200, with the TypeScript code in tsCode, so fix them the way you would fix a tsc error.