Skip to content

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 ​

  1. Failures are visible. A function that can fail declares it in its return type (Result<T, E>), or throws a tracked PropagateError that an upstream boundary is proven to catch.
  2. One way to be missing. Absence is always T | undefined (Option<T>). null is banned so every check and operator speaks one language.
  3. 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 with mut(value).
  4. 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.

GuideWhat you'll learn
Quick startThe five rules you'll meet first, in ten minutes
Adopting SAFE-TSSetup, 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
BunPreloading the Bun transform plugin for bun run, bun test, and Bun.build
EditorThe safe-ts lsp language server: live diagnostics, hover failure sets, quick fixes, and VS Code
ErrorsResult, q(...), PropagateError, unsafe, generators, and boundary handling
Absenceundefined and Option<T> instead of null, optional fields, and nested absence
StateLiving without mutable globals: parameters, Mut<T> loans, factories, and stores
AsyncPromises that can't be lost: await, try, callbacks, and unsafeAsync
Enums and matchEnum<...> and exhaustive match replacing TypeScript enum
JSONValidating untrusted JSON at the boundary with parseJson<T>
Testing with generated dataProperty testing with arbitrary<T>() and check: type-driven generators, shrinking, and seeds
std helpersResult-returning promise combinators, secure random, dictionaries, scoped listeners, and in-place updates
LibrariesAutomatic node_modules analysis, caching, feature packs (Node, Browser, Zod, ws, vue-router), safe-ts coverage, and safe-ts infer
The language's built-insEvery callable ECMAScript built-in classified by failure behavior
How the checker follows pathsControl flow across branches, loops, finally, short-circuits, and callbacks
API changessafe-ts api-diff: detecting breaking public API changes against a git ref
LoopsCompiling 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
ShapesKeeping objects monomorphic on one V8 hidden class
Typing without castsModule augmentation, trust, mapped-type builders, protected members, and clean subclassing
Proof typesHtml, SafeUrl, RegexSource, Ascii, Open<K>, and Patch<T>
Dev checksDevelopment-only runtime assertions stripped from production builds
What the transforms guaranteeExact semantics preserved and altered by each build-time rewrite
What quick fixes keepBehavior-preserving vs intentional-change quick fixes and codemods
Performance mythsOutdated V8 folklore vs optimizations that still pay off
Security scopeWhat 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:

FrameworkCoverage
VueSFC 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.

RuleCatches
no-throwthrow, except of PropagateError subclasses
unhandled-failurecalls that can throw, without handling
must-use-resulta returned Result that is ignored, or kept in a local and never looked at
uncaught-propagationa PropagateError nothing catches
implicit-propagationa method the language calls for you (toString, toJSON, valueOf, [Symbol.iterator], then, [Symbol.dispose], …) that can propagate a PropagateError
floating-rejectionan async failure nobody awaits
floating-promisean async call that can't fail, dropped while the caller goes on
promise-as-valueisErr(load()), `${load()}`, ids.filter(async ...): a promise read as its value
failure-contractan implementation, override or stored callback that fails with more than its interface, base method or type declares (Throws<R, E>)
fetch-signalfetch without a signal: it can wait forever
bounded-concurrencyPromise.all(items.map(...)): every task at once
pending-without-closepending calls settled by message, never on close / error / exit: they wait forever
unbounded-pollwhile (!ready) await tick(): polling with no deadline, attempt limit or AbortSignal
no-mutable-globalmodule-level let/var, mutating module-level values
no-param-mutationchanging or lending (mut(x)) a parameter not declared Mut<T>, also through its methods, a part handed out, or what an object keeps
missing-muta value passed to a Mut<T> parameter or prop without mut(value)
aliased-mutone 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-gettera getter that changes its object
covariant-aliasa Sub[] bound to a writable Base[] local, field, return or property
union-tag-writea write through a union to a property its members type differently (unit.kind = "archer")
readonly-droppeda value with a readonly property given a place where it is writable (const rw: Loose = frozen)
no-mutation-while-iteratingchanging a collection while iterating it
stale-reada local read from a parameter, used after a call that replaced it
no-foreign-prototype-patchBatcher.prototype.begin = ...: patching an imported or global class
no-nullnull
no-undefined-check-for-nullgetItem(k) !== undefined: APIs that return null, checked for undefined
no-null-check-for-undefinednext === null, expect(x).toBeNull(): an Option (no null in its type) checked for null
no-anyany
no-hidden-anyan any nobody wrote: MessageEvent / CustomEvent without a type argument, Function, history.state, event.data in an unannotated listener, workerData
no-unchecked-castas, <T>x, !
no-type-predicatevalue is User, asserts value is User: a claim TypeScript doesn't check the body against
no-overloadfunction parse(text: string): User; over a looser implementation: a result nobody checked
no-unknown-in-resultResult<unknown, E>, Option<unknown>, and a type parameter only the returned Result names
no-nested-optionOption<Option<T>>
no-method-signaturehandle(animal: Animal): string in an interface or type literal; write readonly handle: (animal: Animal) => string
override-parameteran override asking for a narrower parameter than the base method
test-only-helperfixture<T>(...) and other test helpers outside test files
brand-constructorraw as Html, inject<SafeUrl>(key), trust<UserId>(text): a brand made without its constructor
markup-sinkel.innerHTML = text: markup that isn't constant or an Html
url-sinklink.href = url, location.assign(url): a URL that may be javascript:
code-sinksetTimeout(text), setAttribute("onclick", text), import(specifier), vm.runInNewContext(text)
command-sinkexec(`ls ${dir}`): a shell command built from text
path-sinkreadFile(`${root}/${name}`): a path ../ can escape its directory with
pattern-sinktext.search(query), new RegExp(query) in unsafe: a pattern built from text
sql-sinkdb.exec(`... '${name}'`): an SQL statement built from text
brand-sinkpool.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-constructorscalling constructors that aren't declared
no-redosregexes that can take exponential time
sort-comparatorboolean comparators, .sort() on numbers
no-literal-collection-keymap.get([x, y]): always a miss
no-object-dictionaryplain objects keyed by untrusted data
no-for-infor...in (inherited keys)
cycle-init-reada binding read at load through an import cycle (ReferenceError TDZ at startup)
unbound-methodqueueMicrotask(this.tick), const f = obj.m: a method using this, detached from its receiver
number-parse-nanNumber(x), parseInt, Date.parse, new Date(text).getTime(): NaN used unchecked
not-found-indexitems.splice(items.indexOf(item), 1): -1 for "not found" used as a position
regex-last-indexre.test(s) on a g regex in a loop or method where lastIndex carries across strings
use-after-consumea buffer after transfer(), an iterator walked twice, a body read twice, a locked stream, a closed socket or file
stale-across-awaitshared state read before an await and written afterward from that stale read
late-listenerconn.once("close", ...) registered after an await
superseded-task-writea useTask / latest run writing after an await without checking its signal
promise-never-settlesa new Promise with a path that neither resolves nor rejects
unreleased-resourcea file handle, interval, server, or observer not released on some exit path
unbalanced-updatea paired state change and undo where an early exit skips the undo
divide-by-lengthtotal / rows.filter(ok).length: NaN when empty
sparse-array-writeslots[n] = 1 past the end creating sparse holes
keep-error-causereplacing a caught error without { cause }
dataview-endiannessDataView access without an explicit byte order
listener-cleanuplisteners and intervals that can't be removed
prefer-nullish-defaultx || true, n || 10 swallowing falsy values
unreachable-codecode after a never-returning call, or a branch already decided by the type
unknown-eventa listener for an event its platform class never dispatches (safe-ts check only)
unmatched-eventa listener nothing emits for, an emit nobody listens for, and near misses (safe-ts check only)
unused-answername.trim();, encoder.encodeInto(text, out);: a pure/result call whose answer is dropped
misplaced-argumentcorner(x, y) for corner(size, x, y): argument named after a different parameter
decided-testa test whose outcome was just decided by an earlier statement
compare-misses-undefinedid !== "" where id may be undefined
no-math-random-for-secretsMath.random() used for tokens or keys
stable-shapeobjects of one kind constructed with inconsistent keys
hoist-intlIntl formatters rebuilt on every call
no-accumulating-copy[...acc, x] copied on every step of a loop or reduce
import-attributeslegacy assert { type: "json" } syntax
tail-call/** @loop */ on recursion not in tail position
json-literal/** @json */ on values JSON cannot preserve losslessly
duplicate-code-valuetwo codes in a table, union, or switch sharing one value
list-invarianta /** @sorted */ list out of order or /** @unique */ list with duplicates
constructor-calls-overridea constructor calling a method overridden by a subclass before subclass fields initialize (safe-ts check only)
unbounded-spreadMath.max(...values), target.push(...extra): stack overflow past ~100k items
pinned-constant-asserta test asserting a constant's literal value (expect(VERSION).toBe(34))
test-without-assertiona test with an execution path that runs no assertion
assertion-cannot-failexpect(r).toBe(r), constants-only assertions, missing matcher, or mock asserted on itself
deferred-assertionan assertion inside a timer, listener, or unawaited .then running after the test finishes
swallowed-assertionan assertion inside a try whose catch swallows failures
focused-test.only disabling the rest of the test suite
skipped-testa skipped test without a reason (every skip counts as an escape hatch)
duplicate-test-nametwo tests with the same name in one describe
empty-test-suitea describe block or test file containing no tests
q-positionq(...) used in a position the build transform cannot rewrite
q-needs-result-returnq(...) inside a function that doesn't return Result
q-undeclared-errorq(...) propagating an error absent from the function's declared error type
exhaustive-switcha switch on an enum tag, literal union, or code object missing default: unreachable(x)
exhaustive-dispatchan if / ?: chain on a closed set whose fallback swallows unnamed members
negative-member-guardu.phase === Phase.INSIDE && u.job !== Job.FLEE matching future members silently
code-range-comparerange comparisons on unordered code tables without @ordered
inline-member-setduplicated inline member sets drifting across functions (safe-ts check only)
no-ts-enumTypeScript enum declarations
json-typeparseJson<T> called with a type JSON cannot represent
prelude-shadowa local shadowing unsafe, q, match, err, … next to prelude usage
prelude-in-pageprelude helpers referenced inside page.evaluate(fn)
needs-transformq(...), 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-suppressioneslint-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-declarea 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).

RuleCatches
prefer-optionT | undefined instead of Option<T>
no-optional-fieldkey?: T in project types; write key: Option<T> (safe-ts check only)
no-swallowed-errorif (isErr(r)) return undefined: turning a failure into "missing"
sentinel-errorreturning "" for success and a string for errors
wide-parampassing a wide context object when only one or two fields are read
unneeded-muta Mut<T> parameter never mutated, or mut(x) passed to a read-only parameter
prefer-is-over-tagreading .tag directly instead of is(...) / match(...)
prefer-constructor-tagstring tag literals where enum constructors exist
prefer-qmanual if (isErr(x)) return x replaceable by q(x)
prefer-map-errmanual if (isErr(x)) return err(f(x.error))
json-null-in-appJsonNull leaking into application state as a second "none"
null-or-undefined-checkchecking only one of null or undefined when both are possible
undefined-to-nullblanket replacers converting every undefined to null
latest-wins-countermanual request counters replacing useTask / latest
unused-task-signala useTask / latest callback ignoring its AbortSignal
catch-on-result.catch or try wrapping calls that return Result and never reject
misplaced-axios-checkisAxiosError(r.error) on project-owned error values
unsafe-project-callunsafe(() => ownCode()) hiding internal bugs as Err
key-presence-union"field" in choice discriminating unions by key presence
panic-on-loadingpanic when a store isn't hydrated or a loading flag is set
cast-in-testas unknown as T or as never inside test files
strict-truthinessif (count) or v-if="name" hiding 0 or ""
no-positional-childrenpicking child nodes by array index (actor.children[2])
undeclared-return-typefunctions without declared return types whose returns aren't trivially inferred
unused-codeexports nothing imports and dead code reachable only from them (safe-ts check only)
unused-privateunused private class members or write-only fields
string-dispatchplain 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.

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra