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
- Write or edit
.tsusfiles undersrc/. - Run
tsus check --json. Each diagnostic has a stablecode, a position, ahint, and usually afixwith exact text edits. - Run
tsus fixto apply every safe fix (--unsafeadds fixes that can change behavior; review those). Or apply a diagnostic'sfix.editsyourself: each edit replaces[start, end)(UTF-16 offsets into the original file) withnewText. - For anything left, run
tsus explain <CODE>and change the code. Do not work around a rule: there is no suppression comment, andas,anyand!are themselves errors. - Repeat until
tsus checkpasses, thentsus buildemits plain ESM intodist/.tsus checkalso type-checks the project in strict mode; a TypeScript error comes back asTSUS200with the original code intsCode.
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
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: all string literals,
// or all tagged variants. Never string, Error or a mix of the two kinds.
type ParseError = "empty" | "not a number";
type LoadError = Tagged<"EmptyId", string> | Tagged<"NotFound", string> | { tag: "Timeout"; ms: number };
const load = (id: string): Result<User, LoadError> =>
id === "" ? Err(tag("EmptyId", id)) : Err(tag("NotFound", id));Option<T>:Some(value)orNone. Methods:map,andThen,unwrapOr(fallback),okOr(error),isSome(),isNone().Result<T, E>:Ok(value)orErr(error). Methods:map,mapErr,andThen,unwrapOr(fallback),ok(),isOk(),isErr().Tagged<"Name", V>andtag("Name", value)build tagged variants; any object type with a literaltagfield works too.- Behavior lives in functions that take data and return new data:
const rename = (u: User, name: string): User => ({ ...u, name });. - A
voidoperation that can fail returnsResult<true, E>and ends withreturn Ok(true);. - A string literal passed to a generic widens to
string(okOr("empty")isResult<T, string>). Give the type argument (okOr<ParseError>("empty")) or return through a function whose return type names the error.
match
match is a macro and an expression. Each arm is Pattern => expression, separated by commas.
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) {
NotFound(id) => `no user ${id}`, // Tagged variant: binds its value
Timeout(t) => `timed out after ${t.ms}ms`, // plain tagged object: binds the object
_ => "no id given", // wildcard
};
const describe = (e: ParseError): string =>
match (e) {
"empty" => "nothing to parse", // literal patterns
"not a number" => "digits only", // a finite union needs no _
};- Variant patterns:
Some(x),None,Ok(x),Err(e), and any tagVariant(x)of a union with a literaltagfield (binds.valueforTagged, the whole object otherwise). Literal patterns: string, number or boolean literals. One match uses one kind, not both; either kind may end with_. - Matches are checked at compile time: a missing variant is TSUS201, an arm the subject cannot hold is TSUS202. A literal match over a plain
stringneeds_. - Arms are expressions, not blocks. Put multi-step logic in a named function and call it from the arm. Build tagged values in arms with
tag(...), not raw object literals (thetagfield would widen tostring). - Matches nest. An arm may
await; then writeawait 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), never at top level or inside a match arm (TSUS300). Error types must line up: convert with mapErr, or turn an Option into a Result with okOr (TSUS302). In async code ? applies to the awaited value: const user = await load(id)?;. ? binds loosely, so wrap it in parentheses inside larger expressions ((a?) + (b?)), and keep it out of ?: branches, the right side of && || ??, and loop conditions (TSUS303).
const total = (rawA: string, rawB: string): Result<number, ParseError> => {
const a = parse(rawA)?;
const b = parse(rawB)?;
return Ok(a + b);
};
const portOf = (env: Map<string, string>): Result<number, ParseError> => {
const raw = fromNullable(env.get("PORT")).okOr<ParseError>("empty")?;
return parse(raw);
};The boundary
The outside world (npm, DOM, Node, .ts files) returns undefined, throws, and hands you classes. Convert it at the edge:
import { tag, type Tagged } from "@tsus/runtime";
import { fromNullable, wrapSync, wrapAsync, isRecord, asRecord, field } 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));For unknown data use isRecord(v) (a type guard: plain object, not null, not an array), asRecord(v) (Option<Record<string, unknown>>) and field(v, "key") (an own property as Option<unknown>) instead of casts. 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 |
| TSUS200 | Type error | none |
| TSUS201 | Non-exhaustive match | none |
| TSUS202 | Match arm does not fit the subject | none |
| TSUS203 | Match subject is not matchable | none |
| TSUS300 | ? outside a function returning Result or Option | none |
| TSUS301 | ? applied to something that is not a Result or Option | none |
| TSUS302 | ? propagates a value the function cannot return | none |
| TSUS303 | ? in a position that may not run | 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:
{ "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.