Quick start
SAFE-TS keeps you in plain TypeScript—then turns the silent bugs that slip past tsc into fast, actionable diagnostics. Learn the five core rules in about ten minutes.
Five rules in five lines
- Return errors as
Result<T, E>instead of throwing hidden exceptions. - One spelling for absence:
undefined(Option<T>), nevernull. - Don't mutate inputs: return a new value, or explicitly lend with
Mut<T>andmut(x). - Await every promise so failures never escape silently.
- Validate external data at the boundary with
parseJson<T>.
1. Return errors, don't throw them
Nothing in a TypeScript signature tells callers that a function can throw, so callers forget to handle it until production crashes.
✕ Rejectedno-throw
ts
export function parseAge(input: string): number {
const age = Number(input);
if (!Number.isInteger(age)) throw new Error(`not an age: ${input}`);
return age;
}Return the failure instead. Result<number, AgeError> makes the error part of the type, and TypeScript refuses to let callers use the number until they check isErr. Model failures as a named enum and render user-facing messages with match:
✓ Accepted0 diagnostics
ts
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
export type AgeError = Enum<{ NotANumber: { input: string } }>;
export const AgeError = constructors<AgeError>();
export function parseAge(input: string): Result<number, AgeError> {
const age = Number(input);
if (!Number.isInteger(age)) return err(AgeError.NotANumber({ input }));
return age;
}
export function greeting(input: string): string {
const age = parseAge(input);
if (isErr(age)) return match(age.error, { NotANumber: ({ input }) => `Sorry, ${input} is not an age` });
return age >= 18 ? "Welcome" : "Ask a parent";
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
export type AgeError = Enum<{ NotANumber: { input: string } }>;
export const AgeError = constructors<AgeError>();
export function parseAge(input: string): Result<number, AgeError> {
const age = Number(input);
if (!Number.isInteger(age)) return err(({ tag: "NotANumber", input } satisfies AgeError as AgeError));
return age;
}
export function greeting(input: string): string {
const age = parseAge(input);
if (isErr(age)) { const __ms1 = age.error; let __mv1: string; switch (__ms1.tag) { case "NotANumber": { const { input } = __ms1; __mv1 = `Sorry, ${input} is not an age`; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
return age >= 18 ? "Welcome" : "Ask a parent";
}When a function can't handle an error locally, propagate it with q(...) (Rust's ?): const age = q(parseAge(input));. See Errors.
2. Use undefined, not null
JavaScript splits "nothing" across two values, so code inevitably checks for one and receives the other. SAFE-TS bans null and standardizes on undefined, which ?., ??, and optional properties already use.
✕ Rejectedno-null
ts
export function nickname(nicknames: ReadonlyMap<string, string>, id: string): string | null {
return nicknames.get(id) ?? null;
}✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";
export function nickname(nicknames: ReadonlyMap<string, string>, id: string): Option<string> {
return nicknames.get(id);
}See Absence.
3. Return new values, don't mutate inputs
When a function mutates an argument in place, every caller holding a reference to it sees unexpected state changes.
✕ Rejectedno-param-mutation
ts
export function addTag(tags: string[], tag: string): void {
tags.push(tag);
}✓ Accepted0 diagnostics
ts
export function addTag(tags: readonly string[], tag: string): string[] {
return [...tags, tag];
}When in-place mutation is intentional, declare the parameter Mut<T> and lend it explicitly at the call site: addTag(mut(tags), "new"), like Rust's &mut tags. See State.
4. Await your promises
An unawaited promise rejects after its surrounding try has already exited, leaving errors unhandled.
✕ Rejectedfloating-rejection
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
class Offline extends PropagateError {}
async function upload(file: string): Promise<void> {
if (file === "") throw new Offline("no connection");
}
export function save(file: string): void {
try {
upload(file);
} catch {
console.error("never runs");
}
}Return failures as values inside the promise (Promise<Result<T, E>>), await the call, and propagate errors with q(...). Dropped Results are caught too (must-use-result).
✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, q, type Result } from "@evobug_com/safe-ts-std/result";
export type UploadError = Enum<{ Offline: {} }>;
export const UploadError = constructors<UploadError>();
async function upload(file: string): Promise<Result<void, UploadError>> {
return file === "" ? err(UploadError.Offline()) : undefined;
}
export async function save(file: string): Promise<Result<void, UploadError>> {
q(await upload(file));
return undefined;
}ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { err, q, type Result } from "@evobug_com/safe-ts-std/result";
export type UploadError = Enum<{ Offline: {} }>;
export const UploadError = constructors<UploadError>();
async function upload(file: string): Promise<Result<void, UploadError>> {
return file === "" ? err(({ tag: "Offline" } satisfies UploadError as UploadError)) : undefined;
}
export async function save(file: string): Promise<Result<void, UploadError>> {
{ const __q1 = await upload(file); if (__q1 instanceof __qErr) return __q1; __q1; }
return undefined;
}For failures meant to abort an entire command or request (PropagateError), await the call inside the top-level try. See Async.
5. Validate data from outside
JSON.parse can throw on malformed input, and as User blindly trusts whatever shape arrives.
✕ Rejectedunhandled-failureno-unchecked-cast
ts
type User = { readonly name: string };
export function loadUser(text: string): User {
return JSON.parse(text) as User;
}parseJson<User> validates the data against User using a build-time generated validator and returns a Result.
✓ Accepted0 diagnostics
ts
import { parseJson, type JsonError } from "@evobug_com/safe-ts-std/json";
import type { Result } from "@evobug_com/safe-ts-std/result";
type User = { readonly name: string };
export function loadUser(text: string): Result<User, JsonError> {
return parseJson<User>(text);
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { parseJson, type JsonError } from "@evobug_com/safe-ts-std/json";
import type { Result } from "@evobug_com/safe-ts-std/result";
type User = { readonly name: string };
export function loadUser(text: string): Result<User, JsonError> {
return __jsonParse<User>(text, __v0);
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "name": string; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["name"];
if (typeof __j1 !== "string") return __jsonFail(p + ".name", "string", __j1);
const __j2 = __j1;
const out: { "name": string; } = { "name": __j2 };
return out;
}See JSON.
Diagnostic cheatsheet
| Rule | Write instead |
|---|---|
no-throw | return err(...) from a function returning Result |
unhandled-failure | wrap throwing calls in unsafe(() => ...) or try |
must-use-result | propagate with q(...), check isErr(...), or explicitly ignore with void |
no-null | undefined (Option<T>) |
no-unchecked-cast | narrow with a real check, or parseJson<T> for external data |
no-mutable-global | pass state as a parameter |
no-param-mutation | return a new value, or type the parameter Mut<T> |
missing-mut | lend at the call site: addItem(mut(cart), item) |
floating-rejection | await the call |
exhaustive-switch | default: unreachable(value) or match(...) |
Browse all 170 rules in the Rules Explorer. Most findings include one-click quick fixes in your editor and = fix: suggestions in safe-ts check.
Warnings (warning[stable-shape]) report performance or style hazards without failing CI. You can customize any rule's severity per directory in package.json (rule levels), or silence a single line with an explicit reason: // safe-ts-ignore no-null: the SDK distinguishes null from undefined (ignoring one finding).
Opt-in layer: idiomatic rules
Core rules catch defects. A second opt-in layer—the idiomatic rules—enforces one consistent style per concept (Option<T> over T | undefined, q(...) over manual isErr returns, and no swallowed errors). Enable them in package.json with "safe-ts": { "idiomatic": true }, or preview them once with safe-ts check src/main.ts --idiomatic.
Next steps
- Experiment live in the browser playground.
- Configure your project with Adopting SAFE-TS and enable live feedback in your editor. Remember that
q(...)andparseJson<T>rely on the build transform: Vite runs it for apps, Node uses--import @evobug_com/safe-ts-transform/register(Running TypeScript in Node), and Bun preloads its plugin (Bun). - Migrating an existing repo? Start strict on new files with
// @safe-ts legacy(incremental adoption), or run the agent migration skill.