TypeScript-Ultra-Strict
This is my proposal for TypeScript-Ultra-Strict: a stricter TypeScript for a world where AI writes most of the code.
This repo is a thought experiment, not a production tool. The compiler works, type-checks, and every example passes, but the macro syntax is lowered by a preprocessor with known edge cases, the bundler plugins skip semantic checking, there are no published packages, and there is no stability promise. It exists to make the proposal concrete enough to argue with. Do not build anything you care about on it yet.
Status: working prototype. packages/cli implements tsus check and tsus build: a tokenizer built on ts.createScanner, a preprocessor that lowers match and the ? operator with a source map back to the .tsus file, and a full ts.createProgram type-check over the project. match is exhaustiveness-checked at compile time, tsus build emits .js.map files that point at the .tsus source, packages/runtime implements Option/Result, the typed match helpers and the boundary layer, packages/plugin provides webpack/Vite/esbuild/Bun adapters, and all 36 projects under examples/ pass (npm install && npm run examples). LEARNINGS.md documents what broke along the way, how that shaped the design, and the known limitations.
TypeScript's early design decisions assumed humans would write and maintain it, so a lot of features exist to make a human's life easier. We valued speed over quality. With AI writing most of our code, we can flip that tradeoff and force the language to be declarative and verifiable, like Rust.
What changes
- Removes
nullandundefined. In their place,Option<T>andResult<T, E>become first-class types. This is the centerpiece: the removals below only work because these replacements exist. - Removes classes. Data is plain objects; behavior lives in functions.
- Removes
var. - Introduces an SDK for macros, used for pattern matching and variable destructuring over
Option,Result, and tagged unions. (TC39 already has a pattern-matching proposal in the pipeline; this accelerates where the language is heading.)
The interop boundary
Every existing DOM and npm API returns undefined, throws, and hands you classes. Ultra-Strict code never sees those directly. At the boundary, a checked bindings layer converts T | undefined and T | null into Option<T>, and throwing calls into Result<T, E>. Inside the boundary, the strict rules hold everywhere.
Why not just an eslint preset?
Banning classes, nulls, and var can be approximated with tsconfig and lint rules today. Two things need a real compiler:
- The macro SDK. This is the honest cost of the proposal: TypeScript's types are fully erasable, which is why esbuild and swc can strip them in a single fast pass. Macros break that property. The bet is that with AI writing the code, we should spend build-time budget on expressiveness and checkability rather than on keeping type-stripping trivial.
- The boundary layer, which needs type information to generate the
Option/Resultwrappers.
Why TypeScript?
Back in 2008, Google shipped Chrome and V8, and the industry built its edge compute on top of that runtime. Cloudflare Workers runs V8 isolates directly. Node, Deno, and Bun's ecosystem all trace back to it. JavaScript and ESM are the substrate that's already deployed everywhere.
TypeScript is the typed layer the ecosystem already adopted. Rather than asking everyone to move to a new language, Ultra-Strict is a subset-plus-macros of a language AI models already know deeply, targeting a runtime that's already everywhere.
Ideal UX
Any file with a .tsus extension (TypeScript Ultra Strict) is processed under the strict rules and compiled to plain JavaScript. .ts and .tsus files coexist in one project, so adoption is per-file: an AI agent can write new modules in .tsus while the legacy .ts code keeps working untouched. Importing a .tsus module from .ts just works; importing .ts (or any npm package) into .tsus goes through the boundary layer, which rewrites the types so nullable returns arrive as Option<T> and throwing functions arrive as Result<T, E>.
What a .tsus file looks like:
import { readFile } from "node:fs/promises"; // boundary-wrapped: returns Result
type User = { name: string; email: Option<string> };
const loadUser = async (path: string): Promise<Result<User, IoError>> => {
const raw = await readFile(path, "utf8")?; // ? returns the Err early
return parseUser(raw);
};
// macro from the SDK; leaving out an arm is a compile error
const greeting = match (user.email) {
Some(email) => `Reach me at ${email}`,
None => "No email on file",
};How the macros compile
match lowers to a call whose arms are an object keyed by variant tag:
match (opt) { Some(x) => a, None => b } // -> __tsus_match(opt)({ Some: (x) => (a), None: () => (b) })
match (opt) { Some(x) => a, _ => b } // -> __tsus_match_or(opt)({ Some: (x) => (a) }, () => (b))
match (path) { "/" => a, _ => b } // -> __tsus_match_lit(path)([["/", () => (a)]], () => (b))@tsus/runtime types that object with a mapped type over the subject union's tag field, so TypeScript itself requires every variant (unless there is a _ arm), rejects arms the union cannot hold, and narrows each arm's binding to its variant's payload. This works for Option, Result, and any user union with a string tag. Literal patterns lower to a list of [literal, handler] pairs; each literal must be a value of the subject's type, and _ is required unless the literals cover a finite union like "GET" | "POST". When the match has a contextual type (a declared return type, an annotated const, a typed parameter), every arm is checked against it, so Err({ kind: "missing" }) infers the declared error union and a wrong arm is reported on that arm; with no context, the match's type is the union of its arms. If any arm awaits, every arm becomes async and the match is a Promise; await inside a string or comment does not count.
expr? works like Rust's: on an Err or None it returns that value from the enclosing function, otherwise it unwraps.
const port = parsePort(raw)?;
// -> const __tsus_t0 = __tsus_try(parsePort(raw)); if (__tsus_isBail(__tsus_t0)) return __tsus_bail(__tsus_t0); const port = __tsus_t0.value;The enclosing function must declare a Result, Option, or Promise of one as its return type, and the propagated error must fit it. In async code ? applies to the awaited value (await load()?). ? binds like the conditional operator, so it covers everything to its left: write (a()?) + (b()?), not a()? + b()?. Optional chaining (?.), ??, ternaries, and optional properties are untouched.
Diagnostics
| Code | Meaning |
|---|---|
TSUS000 |
Syntax error after macro expansion |
TSUS001-TSUS005 |
Banned class, null, undefined, var, throw |
TSUS006 |
Malformed match (bad pattern, mixed variant and literal patterns, duplicate arm) |
TSUS100 |
Runtime only: a match with no arm for its value (only reachable if the checker was bypassed) |
TSUS200 |
Any TypeScript error, mapped to the .tsus position; tsCode holds the TS code |
TSUS201 |
Non-exhaustive match: missing variants, or literal arms with no _ |
TSUS202 |
A match arm for a variant or literal the subject cannot hold |
TSUS203 |
A match subject that is not a tagged union or a literal type |
TSUS300 |
? outside a function declaring a Result/Option return type (or at top level, or in a match arm) |
TSUS301 |
? applied to something that is not a Result or Option |
TSUS302 |
? propagating an Err/None the function's return type cannot hold |
TSUS303 |
? in a position that may not run (?: branch, right of &&/||/??, loop condition) |
Every TypeScript-derived code (TSUS2xx, TSUS301, TSUS302) carries the original TS code as tsCode in tsus check --json.
Framework integrations
packages/plugin (@tsus/plugin) is one transform core with a thin adapter per host, all sharing the CLI's preprocessor and checker:
@tsus/plugin/webpack: a loader. In Next.js, one rule innext.config.mjsmakes.tsusimportable from any page or component (examples/27-nextjs, verified bynext buildemitting the rendered string into static HTML).@tsus/plugin/vite: a Vite plugin, which also covers Astro, SvelteKit, and Nuxt through theirvite.pluginsconfig (examples/28-astro).@tsus/plugin/esbuild: an esbuild plugin. Bun's plugin API is esbuild-shaped, so the same object registers withBun.plugin; with a one-linebunfig.tomlpreload,bun runexecutes.tsusimports natively with no build step (examples/29-bun).
The adapters deliberately leave import specifiers untouched: the host bundler resolves .tsus to .tsus chains through its own pipeline and each hop hits the transform again. The tsus CLI stays the standalone path (and the CI path, via tsus check --json).
Tooling:
tsus buildcompiles to JS with source maps,tsus checktype-checks without emitting. Both run as an esbuild/swc plugin so existing bundler setups pick up.tsusfiles without config changes. (Today the plugins run the syntactic rules only; the semantic type-check lives intsus check.)- Editor support ships as a TypeScript language service plugin, so VS Code and every TS-aware editor get diagnostics, go-to-definition, and macro expansion previews for free.
- Diagnostics are machine-first: every error has a stable code, a JSON output mode, and a suggested fix, so an agent can consume
tsus check --jsonin a loop without parsing prose. Human-readable output is a rendering of the same data. - No new package manager and no new registry. npm packages work through the boundary layer, and published
.tsuspackages ship compiled JS plus.d.tsfiles, so consumers don't need to know the source language existed.
Evidence
evals/ holds a harness that tests the thesis directly: a model writes the same 30 small programs (config parsing, an LRU cache, retries with typed errors, a state machine, date ranges, an inventory ledger, and so on) in .ts and in .tsus, the compiler's errors go back to it for up to three repair rounds, and hidden tests the model never sees decide which version is correct. The tasks were chosen because null, undefined, exceptions and unhandled cases cause real bugs in them. Every task ships a reference solution in both languages and a plausible buggy solution that the hidden tests must catch (node evals/validate.mjs).
Results are in evals/RESULTS.md. So far that file holds only the harness self-test, which runs the reference solutions through the pipeline and says nothing about the thesis. No model run has been recorded yet; node evals/run.mjs --pilot runs the 10-task pilot once the Claude Code CLI is logged in or ANTHROPIC_API_KEY is set. Even then, one model, one sample per task and 10 to 30 tasks is a pilot, not proof. evals/README.md lists the caveats, starting with this one: results recorded before the compiler foundation landed came from a tsus checker that did not type-check, so .ts got more compile-time help than .tsus; tsus check now runs a full TypeScript type-check too.
Known limitations
The four limitations the MVP shipped with are closed: tsus check type-checks the whole project with ts.createProgram, a non-exhaustive match is a compile-time TSUS201, await in arms is detected on the parsed AST, and the tokenizer is TypeScript's own scanner with regex and template rescanning. What is still rough, roughly in order of how likely it is to bite:
- The bundler plugins (
@tsus/plugin/*) transform one file at a time and only run the syntactic rules. Type errors surface intsus check, not innext buildorvite build. tsus checkuses fixed compiler options (strict, ES2022, bundler resolution, DOM and Node types) and ignores anytsconfig.json.?binds like the conditional operator, soa()? + 1is a syntax error; write(a()?) + 1. It cannot appear in a match arm (arms are closures), a?:branch, the right side of&&/||/??, or a loop condition. Its return-type check is syntactic: the declared type must be spelledResult<...>,Option<...>, orPromise<...>of one, not an alias.- Regex detection is a one-token lookbehind: after
)or}a/is read as division, soif (x) /re/.test(s)misparses. Commas in an arm body's type arguments are handled by a heuristic, and an arm body cannot be a statement block.
The examples
examples/ is the test suite: 36 small projects, each with an example.json declaring what must happen. npm run examples builds and executes all of them and fails on any drift.
Core language and runtime
| Example | Shows |
|---|---|
01-hello |
Smallest possible .tsus file compiling to plain ESM |
02-option-basics |
Option<T> with map/andThen/unwrapOr |
03-result-basics |
Result<T, E> with map/mapErr |
04-match-option, 05-match-result |
The match macro over Some/None and Ok/Err |
06-tagged-union |
User-defined tagged unions with a _ wildcard arm |
32-regex-literals |
Regex literals containing braces, quotes, a backtick, and a fake match block |
33-await-in-string |
await inside a string in an arm stays synchronous; a real await makes the match async |
34-try-operator |
? on Result and Option, several per expression, in async functions, next to ?., ??, and ternaries |
36-literal-patterns |
Literal arms over string, number, and boolean subjects; finite unions need no _; arms typed by the declared return type |
Rejected on purpose (these pass by failing the checker with the right code)
| Example | Code |
|---|---|
07-banned-null |
TSUS002 |
08-banned-class |
TSUS001 |
09-banned-var |
TSUS004 |
10-banned-undefined |
TSUS003 |
11-banned-throw |
TSUS005 |
30-non-exhaustive-match |
TSUS201, for a missing tagged-union variant, a missing Err, and literal arms that miss a union member |
31-wrong-arm-type |
TSUS200 (an arm of the wrong type, a payload used as the wrong type) and TSUS202 (a misspelled variant) |
35-try-misuse |
TSUS300, TSUS301, TSUS302, TSUS303 |
Rejection examples can also pin exact positions ("diagnostics": [{ "code", "file", "line", "col", "tsCode" }] in example.json), which tests the source map back to the .tsus file.
Interop and stress
| Example | Shows |
|---|---|
12-tsus-imports-tsus, 20-deep-chain |
.tsus import chains, four levels deep |
13-tsus-imports-ts, 14-ts-imports-tsus |
Mixed projects in both directions; .ts keeps its classes and nulls |
15-npm-dependency |
zod feeding Result |
16-boundary-fs, 26-json-boundary |
wrapAsync/wrapSync turning throws into Result |
17-nested-match, 18-generics, 19-async-result |
Nested matches, generic signatures, await inside match arms |
21-circular-imports |
Function-level .tsus cycles (fine, because ESM) |
22-mixed-project |
ts + tsus + zod + boundary in one project |
24-hostile-syntax |
Decoy match blocks in strings, comments, and template literals |
25-shadowed-match |
A user function named match staying a plain call |
Runtimes and frameworks
| Example | Shows |
|---|---|
23-cloudflare-worker |
Cloudflare { fetch } module shape, tested against real Request/Response |
27-nextjs |
Next.js 14 via the webpack loader; next build renders .tsus output into static HTML |
28-astro |
Astro 4 via the Vite plugin, verified in built HTML |
29-bun |
Bun runs .tsus imports natively via a bunfig.toml preload, no build step |