SAFE-TS Overview
SAFE-TS is a strict, Rust-inspired subset of TypeScript. It doesn't introduce a custom language: everything you write remains plain TypeScript that tsc --strict still checks. A fast Rust static analyzer (built on oxc) enforces rules on top—turning production crashes into immediate editor and CI diagnostics.
It is built for code that AI agents write. Strict rules that feel verbose to a person cost an agent nothing when the feedback loop runs in milliseconds and every diagnostic explains what failed, why, and what to write instead. Because an agent optimizes for "the checker passes", SAFE-TS focuses on deep whole-program static analysis that closes workarounds and counts every escape hatch.
Four guarantees
- Failures are visible. A function that can fail declares it in its return type (
Result<T, E>), or throws a trackedPropagateErrorthat an upstream boundary is proven to catch. - One way to be missing. Absence is always
T | undefined(Option<T>).nullis banned so every check and operator speaks one language. - Explicit ownership and mutation. Functions take inputs and return updated values. Nothing is mutated at module level or through a parameter unless its type declares
Mut<T>and the caller lends it withmut(value). - Validated external boundaries. Data from JSON, files, or the network is validated against your TypeScript types before code trusts it, using build-time generated validators and proof brands.
What it guarantees—and what it doesn't
SAFE-TS checks everything it can see statically: unhandled failures in your code, ECMAScript built-ins (JSON.parse, new URL, …), and third-party libraries (analyzed directly from node_modules or described by a feature pack).
It does not prove a program can never crash. Logic mistakes, infinite loops, out-of-memory conditions, or a dependency behaving differently from its source or feature pack remain outside static reach. Every rule page includes a What the rule can't see section so the boundary is always explicit.
Guides
Each guide teaches the SAFE-TS pattern that replaces what the rules forbid.
| Guide | What you'll learn |
|---|---|
| Quick start | The five rules you'll meet first, in ten minutes |
| Adopting SAFE-TS | Setup, Node loader, safe-ts check in CI, prelude, incremental legacy migration, rule levels, codemods, and escape-hatch baselines |
| Migrating with an agent | @evobug_com/safe-ts-skill: an agent skill that writes a target architecture, runs a census, and migrates behind gates |
| Bun | Preloading the Bun transform plugin for bun run, bun test, and Bun.build |
| Editor | The safe-ts lsp language server: live diagnostics, hover failure sets, quick fixes, and VS Code |
| Errors | Result, q(...), PropagateError, unsafe, generators, and boundary handling |
| Absence | undefined and Option<T> instead of null, optional fields, and nested absence |
| State | Living without mutable globals: parameters, Mut<T> loans, factories, and stores |
| Async | Promises that can't be lost: await, try, callbacks, and unsafeAsync |
| Enums and match | Enum<...> and exhaustive match replacing TypeScript enum |
| JSON | Validating untrusted JSON at the boundary with parseJson<T> |
| Testing with generated data | Property testing with arbitrary<T>() and check: type-driven generators, shrinking, and seeds |
| std helpers | Result-returning promise combinators, secure random, dictionaries, scoped listeners, and in-place updates |
| Libraries | Automatic node_modules analysis, caching, feature packs (Node, Browser, Zod, ws, vue-router), safe-ts coverage, and safe-ts infer |
| The language's built-ins | Every callable ECMAScript built-in classified by failure behavior |
| How the checker follows paths | Control flow across branches, loops, finally, short-circuits, and callbacks |
| API changes | safe-ts api-diff: detecting breaking public API changes against a git ref |
| Loops | Compiling array method chains into tight loops at build time; InlineArray for chains that always are |
| Inlining functions | @inline functions expanded at call sites by arity |
| Shapes | Keeping objects monomorphic on one V8 hidden class |
| Typing without casts | Module augmentation, trust, mapped-type builders, protected members, and clean subclassing |
| Proof types | Html, SafeUrl, RegexSource, Ascii, Open<K>, and Patch<T> |
| Dev checks | Development-only runtime assertions stripped from production builds |
| What the transforms guarantee | Exact semantics preserved and altered by each build-time rewrite |
| What quick fixes keep | Behavior-preserving vs intentional-change quick fixes and codemods |
| Performance myths | Outdated V8 folklore vs optimizations that still pay off |
| Security scope | What SAFE-TS protects against—and what stays out of scope |
Frameworks
Each framework has a dedicated branded section with its own rules and runtime helpers:
| Framework | Coverage |
|---|---|
| Vue | SFC templates checked as code, per-instance state, borrowed props, useTask + <Match>, live comparison demo, and 23 Vue rules |
| React | .tsx components and custom hooks, event handler Results, useTask + <Match>, effect cleanup, and 4 React rules |
Rules
Looking for a specific rule? Use the searchable Rules Explorer to filter all 170 rules by category, severity, or quick-fix support, or browse the complete catalog below.
| Rule | Catches |
|---|---|
no-throw | throw, except of PropagateError subclasses |
unhandled-failure | calls that can throw, without handling |
must-use-result | a returned Result that is ignored, or kept in a local and never looked at |
uncaught-propagation | a PropagateError nothing catches |
implicit-propagation | a method the language calls for you (toString, toJSON, valueOf, [Symbol.iterator], then, [Symbol.dispose], …) that can propagate a PropagateError |
floating-rejection | an async failure nobody awaits |
floating-promise | an async call that can't fail, dropped while the caller goes on |
promise-as-value | isErr(load()), `${load()}`, ids.filter(async ...): a promise read as its value |
failure-contract | an implementation, override or stored callback that fails with more than its interface, base method or type declares (Throws<R, E>) |
fetch-signal | fetch without a signal: it can wait forever |
bounded-concurrency | Promise.all(items.map(...)): every task at once |
pending-without-close | pending calls settled by message, never on close / error / exit: they wait forever |
unbounded-poll | while (!ready) await tick(): polling with no deadline, attempt limit or AbortSignal |
no-mutable-global | module-level let/var, mutating module-level values |
no-param-mutation | changing or lending (mut(x)) a parameter not declared Mut<T>, also through its methods, a part handed out, or what an object keeps |
missing-mut | a value passed to a Mut<T> parameter or prop without mut(value) |
aliased-mut | one call that lends x with mut(x) and also gets x or a part of it, or two loans alive at once, or the owner writing it while lent |
mutating-getter | a getter that changes its object |
covariant-alias | a Sub[] bound to a writable Base[] local, field, return or property |
union-tag-write | a write through a union to a property its members type differently (unit.kind = "archer") |
readonly-dropped | a value with a readonly property given a place where it is writable (const rw: Loose = frozen) |
no-mutation-while-iterating | changing a collection while iterating it |
stale-read | a local read from a parameter, used after a call that replaced it |
no-foreign-prototype-patch | Batcher.prototype.begin = ...: patching an imported or global class |
no-null | null |
no-undefined-check-for-null | getItem(k) !== undefined: APIs that return null, checked for undefined |
no-null-check-for-undefined | next === null, expect(x).toBeNull(): an Option (no null in its type) checked for null |
no-any | any |
no-hidden-any | an any nobody wrote: MessageEvent / CustomEvent without a type argument, Function, history.state, event.data in an unannotated listener, workerData |
no-unchecked-cast | as, <T>x, ! |
no-type-predicate | value is User, asserts value is User: a claim TypeScript doesn't check the body against |
no-overload | function parse(text: string): User; over a looser implementation: a result nobody checked |
no-unknown-in-result | Result<unknown, E>, Option<unknown>, and a type parameter only the returned Result names |
no-nested-option | Option<Option<T>> |
no-method-signature | handle(animal: Animal): string in an interface or type literal; write readonly handle: (animal: Animal) => string |
override-parameter | an override asking for a narrower parameter than the base method |
test-only-helper | fixture<T>(...) and other test helpers outside test files |
brand-constructor | raw as Html, inject<SafeUrl>(key), trust<UserId>(text): a brand made without its constructor |
markup-sink | el.innerHTML = text: markup that isn't constant or an Html |
url-sink | link.href = url, location.assign(url): a URL that may be javascript: |
code-sink | setTimeout(text), setAttribute("onclick", text), import(specifier), vm.runInNewContext(text) |
command-sink | exec(`ls ${dir}`): a shell command built from text |
path-sink | readFile(`${root}/${name}`): a path ../ can escape its directory with |
pattern-sink | text.search(query), new RegExp(query) in unsafe: a pattern built from text |
sql-sink | db.exec(`... '${name}'`): an SQL statement built from text |
brand-sink | pool.query(text) after brandSinks("Sql", ["pg Pool#query"]): not the required brand |
inline | /** @inline */ on code that can't become a loop (or a chain on an InlineArray that can't), or a function that can't be inlined |
enum-constructors | calling constructors that aren't declared |
no-redos | regexes that can take exponential time |
sort-comparator | boolean comparators, .sort() on numbers |
no-literal-collection-key | map.get([x, y]): always a miss |
no-object-dictionary | plain objects keyed by untrusted data |
no-for-in | for...in (inherited keys) |
cycle-init-read | a binding read at load through an import cycle (ReferenceError TDZ at startup) |
unbound-method | queueMicrotask(this.tick), const f = obj.m: a method using this, detached from its receiver |
number-parse-nan | Number(x), parseInt, Date.parse, new Date(text).getTime(): NaN used unchecked |
not-found-index | items.splice(items.indexOf(item), 1): -1 for "not found" used as a position |
regex-last-index | re.test(s) on a g regex in a loop or method where lastIndex carries across strings |
use-after-consume | a buffer after transfer(), an iterator walked twice, a body read twice, a locked stream, a closed socket or file |
stale-across-await | shared state read before an await and written afterward from that stale read |
late-listener | conn.once("close", ...) registered after an await |
superseded-task-write | a useTask / latest run writing after an await without checking its signal |
promise-never-settles | a new Promise with a path that neither resolves nor rejects |
unreleased-resource | a file handle, interval, server, or observer not released on some exit path |
unbalanced-update | a paired state change and undo where an early exit skips the undo |
divide-by-length | total / rows.filter(ok).length: NaN when empty |
sparse-array-write | slots[n] = 1 past the end creating sparse holes |
keep-error-cause | replacing a caught error without { cause } |
dataview-endianness | DataView access without an explicit byte order |
listener-cleanup | listeners and intervals that can't be removed |
prefer-nullish-default | x || true, n || 10 swallowing falsy values |
unreachable-code | code after a never-returning call, or a branch already decided by the type |
unknown-event | a listener for an event its platform class never dispatches (safe-ts check only) |
unmatched-event | a listener nothing emits for, an emit nobody listens for, and near misses (safe-ts check only) |
unused-answer | name.trim();, encoder.encodeInto(text, out);: a pure/result call whose answer is dropped |
misplaced-argument | corner(x, y) for corner(size, x, y): argument named after a different parameter |
decided-test | a test whose outcome was just decided by an earlier statement |
compare-misses-undefined | id !== "" where id may be undefined |
no-math-random-for-secrets | Math.random() used for tokens or keys |
stable-shape | objects of one kind constructed with inconsistent keys |
hoist-intl | Intl formatters rebuilt on every call |
no-accumulating-copy | [...acc, x] copied on every step of a loop or reduce |
import-attributes | legacy assert { type: "json" } syntax |
tail-call | /** @loop */ on recursion not in tail position |
json-literal | /** @json */ on values JSON cannot preserve losslessly |
duplicate-code-value | two codes in a table, union, or switch sharing one value |
list-invariant | a /** @sorted */ list out of order or /** @unique */ list with duplicates |
constructor-calls-override | a constructor calling a method overridden by a subclass before subclass fields initialize (safe-ts check only) |
unbounded-spread | Math.max(...values), target.push(...extra): stack overflow past ~100k items |
pinned-constant-assert | a test asserting a constant's literal value (expect(VERSION).toBe(34)) |
test-without-assertion | a test with an execution path that runs no assertion |
assertion-cannot-fail | expect(r).toBe(r), constants-only assertions, missing matcher, or mock asserted on itself |
deferred-assertion | an assertion inside a timer, listener, or unawaited .then running after the test finishes |
swallowed-assertion | an assertion inside a try whose catch swallows failures |
focused-test | .only disabling the rest of the test suite |
skipped-test | a skipped test without a reason (every skip counts as an escape hatch) |
duplicate-test-name | two tests with the same name in one describe |
empty-test-suite | a describe block or test file containing no tests |
q-position | q(...) used in a position the build transform cannot rewrite |
q-needs-result-return | q(...) inside a function that doesn't return Result |
q-undeclared-error | q(...) propagating an error absent from the function's declared error type |
exhaustive-switch | a switch on an enum tag, literal union, or code object missing default: unreachable(x) |
exhaustive-dispatch | an if / ?: chain on a closed set whose fallback swallows unnamed members |
negative-member-guard | u.phase === Phase.INSIDE && u.job !== Job.FLEE matching future members silently |
code-range-compare | range comparisons on unordered code tables without @ordered |
inline-member-set | duplicated inline member sets drifting across functions (safe-ts check only) |
no-ts-enum | TypeScript enum declarations |
json-type | parseJson<T> called with a type JSON cannot represent |
prelude-shadow | a local shadowing unsafe, q, match, err, … next to prelude usage |
prelude-in-page | prelude helpers referenced inside page.evaluate(fn) |
needs-transform | q(...), parseJson<T>, or prelude names imported by a Vite config running without the transform |
safe-ts-ignore | // safe-ts-ignore missing a rule name, missing a reason, or silencing nothing |
no-ts-suppression | @ts-nocheck, @ts-ignore, or @ts-expect-error without a reason |
no-lint-suppression | eslint-disable / oxlint-disable without a rule name or targeting a safe-ts/ rule |
unlisted-marker | // @safe-ts std or // @safe-ts legacy in a file unlisted in package.json |
no-unchecked-declare | a declare asserting a value type nothing verifies |
Idiomatic rules (opt-in)
Off by default; enable with "safe-ts": { "idiomatic": true } in package.json, or try them once with safe-ts check --idiomatic (Adoption).
| Rule | Catches |
|---|---|
prefer-option | T | undefined instead of Option<T> |
no-optional-field | key?: T in project types; write key: Option<T> (safe-ts check only) |
no-swallowed-error | if (isErr(r)) return undefined: turning a failure into "missing" |
sentinel-error | returning "" for success and a string for errors |
wide-param | passing a wide context object when only one or two fields are read |
unneeded-mut | a Mut<T> parameter never mutated, or mut(x) passed to a read-only parameter |
prefer-is-over-tag | reading .tag directly instead of is(...) / match(...) |
prefer-constructor-tag | string tag literals where enum constructors exist |
prefer-q | manual if (isErr(x)) return x replaceable by q(x) |
prefer-map-err | manual if (isErr(x)) return err(f(x.error)) |
json-null-in-app | JsonNull leaking into application state as a second "none" |
null-or-undefined-check | checking only one of null or undefined when both are possible |
undefined-to-null | blanket replacers converting every undefined to null |
latest-wins-counter | manual request counters replacing useTask / latest |
unused-task-signal | a useTask / latest callback ignoring its AbortSignal |
catch-on-result | .catch or try wrapping calls that return Result and never reject |
misplaced-axios-check | isAxiosError(r.error) on project-owned error values |
unsafe-project-call | unsafe(() => ownCode()) hiding internal bugs as Err |
key-presence-union | "field" in choice discriminating unions by key presence |
panic-on-loading | panic when a store isn't hydrated or a loading flag is set |
cast-in-test | as unknown as T or as never inside test files |
strict-truthiness | if (count) or v-if="name" hiding 0 or "" |
no-positional-children | picking child nodes by array index (actor.children[2]) |
undeclared-return-type | functions without declared return types whose returns aren't trivially inferred |
unused-code | exports nothing imports and dead code reachable only from them (safe-ts check only) |
unused-private | unused private class members or write-only fields |
string-dispatch | plain string compared against three or more literals instead of a closed set |
Every example is tested
Every code block in this documentation is verified continuously. Accepted blocks produce zero SAFE-TS diagnostics and adhere to the architecture taught in the guides; rejected blocks must trigger the exact rules listed on their header—while still compiling under tsc --strict (or vue-tsc with strict templates for Vue SFCs). Run cargo test --test docs and npm run test:docs to execute the full verification suite.