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 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
import { 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
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: thevaluefield if the variant has one, elseerror, 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 isTSUS201), an arm for a variant the type does not have isTSUS202, 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 plainstringornumberthey always need_. - When the match has a declared type (a function return type, an annotated
const), every arm is checked against it, soErr({ 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: writeawait match (x) { ... }. matchonly fires asmatch (expr) {. A method call likestr.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:
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 returningResult<T, number>, andNonecan only propagate out of a function returningOption(TSUS302). Convert first withmapErrorokOr. ?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/Optionreturn type, or inside a match arm (TSUS300); not on a value that is not aResult/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)returnsResult<any, Error>; likewisewrapSync(decodeURIComponent)(s).wrapAsync(fn)does the same for async functions and returnsPromise<Result<...>>. - Values typed
unknown(parsed JSON, request bodies): check withtypeof,Array.isArray,Number.isInteger, andfromNullablefor missing keys.typeof v === "undefined"is a string comparison and is allowed, butfromNullable(v).isNone()reads better.
Inside the boundary, everything you write returns Option or Result, never undefined and never an exception.
A complete example
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 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.