Skip to content

The language's built-ins ​

JSON.parse is only one of hundreds of standard JavaScript callables that throw. prices.reduce((a, b) => a + b) throws a TypeError on an empty array, new Date(input).toISOString() throws a RangeError on invalid dates, " ".repeat(n) throws on negative counts, and bigint division throws on 0n—all accepted silently by tsc --strict. SAFE-TS ships a complete failure map of ECMAScript built-ins so unhandled-failure flags unguarded calls automatically.

In short

  • Complete ECMAScript coverage: crates/safe_ts_core/ecmascript/ecmascript-api.json classifies all 1,110 callables declared in lib.es*.d.ts (Intl, typed arrays, DataView, Atomics, Temporal), verified by runtime tests on Node.
  • Silent when proven safe: calls with an initial value on reduce, a non-empty array check, a Number.isNaN(date.getTime()) guard, or in-range literal arguments (n.toFixed(2)) pass cleanly.
  • Strict on dynamic inputs: arguments coming from parameters or external data (n.toFixed(digits)) are reported unless bounded or handled.
  • Consistent handling: works seamlessly with unsafe(() => ...), try, cross-file failure traces, and root-cause grouping.

The map ​

Every callable of the libs lib.esnext.d.ts references (global functions, constructors, calling a constructor without new, static and prototype methods, the members of Math, JSON, Reflect, Atomics, Intl and Temporal) is in exactly one category, the same ones the Node and browser maps use:

CategoryMeaningCount
throwsthrows for values its types allow: the receiver's state (an empty list, an invalid date, a view shorter than the read), an argument's value (a count, digits, a radix, a code point, a locale or time zone, text to parse)290
propagatesruns your code (a callback, an executor, a getter, a generator's body) and throws what it throws, nothing of its own (map, forEach, Promise.all, Function#call)224
returnsreports failure in its return value: NaN (parseInt, Date.parse), an invalid Date (new Date(text)), null (Date#toJSON), false (Reflect.set)12
argsthrows only when called wrongly: argument types TypeScript checks, values the program itself writes (a non-global RegExp for replaceAll), misuse (Temporal.*#valueOf always throws)45
neverdoesn't fail, short of the engine's limits539

A member whose only failure is a result past the engine's limits (a string longer than about a billion characters, an array past 2^32 - 1 elements: padStart, concat, push, join) is never, as a + b and [...a, ...b] are, and listed in the map's limits. The map also lists the operators that throw (bigint / bigint, %, **) and, in platform, the web globals Node and browsers both have that SAFE-TS reports without a pack (atob, btoa, structuredClone, new URL). It is the one source: the checker reads it (crates/safe_ts_core/src/builtins.rs). Its consumes section says which built-ins use a value up (ArrayBuffer#transfer, an iteration of a one-shot iterator, a transfer list), for use-after-consume (the format).

errors says what each failing member throws, in the packs' notation (RangeError, SyntaxError | RangeError | TypeError, TypeError | (what the callback throws)), and conditions when. crates/safe_ts_core/ecmascript/errors.test.ts (run by npm run test:std) checks the map against the installed TypeScript (every callable, once) and makes every failing member fail on the running Node: all 290 members that throw, and the four web globals, with the error's class the text names and nothing it doesn't (no code, no other property). None is written from the specification alone. node crates/safe_ts_core/ecmascript/inventory.ts lists what a TypeScript upgrade added or removed; node crates/safe_ts_core/ecmascript/triggers.ts prints what each trigger throws.

Callbacks read right away ​

The map's callbacks lists the members that read what a callback returns before a promise it returns can settle, so an async callback hands them a promise where they read a value, and what each does with it: truthiness (filter, some, every, find, findIndex, findLast, findLastIndex, of arrays, typed arrays and iterators: a promise passes every test), accumulator (reduce, reduceRight: the next step gets the promise), key (Map.groupBy, Object.groupBy), value (JSON.parse's reviver, JSON.stringify's replacer), collected (map, flatMap, Array.from: an array of promises), dropped (forEach, new Promise's executor: nobody waits), and the ones lib types, so that TypeScript refuses an async callback itself: order (sort, toSorted), number (a typed array's map and from; a bigint array throws instead), text (replace, replaceAll). promise-as-value reads it, by method name (the receiver's type isn't known). crates/safe_ts_core/ecmascript/callbacks.test.ts calls each one with an async callback on the running Node and checks what it does with the promise. The platform's callbacks (event listeners, observers, timers) are called later, not read: a promise they return floats, which is floating-rejection's when it can reject; the platform's forEach methods (NodeList, Headers, FormData) are matched by name with the rest.

What a member answers ​

The map's answers says which members have no effect but their answer, for unused-answer: a call of one as a statement of its own throws away all it did (name.trim();, list.concat(more);, Math.max(a, b);). The list isn't written by hand. crates/safe_ts_core/ecmascript/answers.ts calls every member of never, args, returns, throws and propagates on sample receivers (lists, strings, numbers, dates, patterns, maps, sets, buffers, typed arrays, Intl and Temporal values) with sample arguments, a fresh receiver and fresh arguments each time, and keeps a member that answered something other than undefined or a promise and changed neither its receiver nor an argument: the elements, own properties, entries, bytes, a date's time, a pattern's lastIndex, whether an object is frozen, sealed or extensible, a buffer's length. 875 members pass; the 152 that change something (push, sort, set, add, Date#setHours, RegExp#test on a global pattern, Object.freeze, Reflect.set) or answer nothing (forEach) don't, nor 15 no sample call reached (left out, not guessed), nor the 68 of the scopes whose effects no snapshot shows: an iterator's or generator's position, a weak collection's contents, code a member runs that isn't an argument (Function#call, Reflect.apply), Atomics.wait and notify, and promises (the promise rules'). node crates/safe_ts_core/ecmascript/answers.ts --write writes the list; answers.test.ts (run by npm run test:std) measures again and fails when the list differs.

answers.tells lists members that do something and answer whether, or how much of, it happened: Atomics.compareExchange (it wrote only if it found the value expected) and TextEncoder#encodeInto ({ read, written }: what doesn't fit is left out), a web class both runtimes have, named in answers.globals so it counts without a pack. The browser and Node packs' maps have their own answers.tells (the format).

What is reported ​

The map's checks say, for each member unhandled-failure reports, what a call must show to be unable to fail. A method is never matched by its name alone: it is reported when the receiver's class is known, from a declared type (prices: readonly number[], n: number, a field or a function's return type declared in another file), a literal, or how the value is made (new Date(...), new DataView(...), xs.map(...)). A receiver of no known type isn't reported.

The receiver's state ​

  • reduce / reduceRight without an initial value (arrays, typed arrays, iterators) can't fail on a list known to have an element: an array literal with one, a tuple type that starts with a required element (readonly [number, ...number[]]), what .map makes of one, or a list checked first (if (list.length === 0) return ..., list.length > 0 && ...), the same checks a[i]! is proved with.
  • toISOString (and toTemporalInstant) can't fail on a date made from the clock (new Date()), from a literal number or ISO text (new Date("2026-11-21")), or checked: if (Number.isNaN(date.getTime())) return ...;, Number.isFinite(date.getTime()) ? ... : ... (also Number.isInteger, and String(date) === "Invalid Date": the checks number-parse-nan takes for a number read from the date, so one check clears both). A date parsed from text is reported: new Date(input), new Date(row.at) with at declared string in another file, and one step away, a date made from a number parsed from text (new Date(Date.parse(input)), Number(input), parseInt, +input, or a const holding one, unless it was checked with Number.isNaN(ms) first) or what a function of the project returns when that function returns such a date (parseStamp(input).toISOString(), in the same file or another, also through a function that returns another's date). The message says where that date is made. A check in the function before it returns the date, or in the caller before it uses it, clears it. The same goes for formatter.format(date).
  • A DataView read or write (getUint32(offset), ...) can't fail on a view whose length is written (new DataView(new ArrayBuffer(8))) at an offset that fits. A view made in the function over a buffer it was given (new DataView(buffer).getUint32(0, true)) is reported when the function reads neither the buffer's length nor the view's.
  • An index into a list (list.with(i, v), Atomics.load(shared, i)) can't fail when it is proved within the list, written in the code, or not from data (below).

An argument's value ​

The Node and browser maps put "fails only on wrong arguments" in args, which isn't reported: a wrong argument is the programmer's mistake. That holds when the programmer wrote the argument, and not when it is data. An argument can't make the call fail when it is written in the code (a literal, a const bound to one, an object or array literal of those), checked against the range just before the call, or computed by the function from what it holds itself; it can when it comes from data: a parameter of the function (what a caller supplies), something read off one or off this, or text turned into a number or parsed (Number(text), parseInt, JSON.parse). So n.toFixed(2) can't fail and n.toFixed(digits) with digits a parameter can; " ".repeat(Math.max(0, 10 - label.length)) can't, " ".repeat(width - text.length) with width a parameter can. A literal the checker can read and knows to be wrong (n.toFixed(101), a malformed locale tag, a time zone that doesn't exist) is reported wherever it is.

Checked first means a comparison the code makes before the call, as for a[i]!: if (digits < 0 || digits > 100) return ...;, inside if (radix >= 2 && radix <= 36), or Number.isInteger(code) && code >= 0 && code <= 0x10ffff && .... Where NaN would throw too (toString(radix), toPrecision, fromCodePoint, new Array(n)), the check must be one that NaN fails: a comparison that held, or Number.isInteger; an early exit on x < lo || x > hi lets NaN through.

Built-inThrows whenCan't fail with
n.toFixed(d), toExponential(d)d outside 0..100a literal, or d checked in range
n.toPrecision(p)p outside 1..100the same, NaN excluded
n.toString(radix), bigint's tooradix outside 2..36the same, NaN excluded
s.repeat(count)count negative or infinitea literal, a clamp (Math.max(0, ...) of known parts); to pad, padStart / padEnd, which can't fail
s.normalize(form)form not NFC, NFD, NFKC, NFKDthe form written out
String.fromCodePoint(...codes)a code that isn't an integer in 0..0x10FFFFcodes checked first
new Array(n), Array(n)one number argument that isn't an integer in 0..2^32 - 1a literal, a length, n checked with Number.isInteger
BigInt(x)text that isn't an integer, a number that isn't one, undefinedan integer literal, a bigint, a boolean, integer text, a length
BigInt.asIntN(bits, x)bits negative or above 2^53 - 1a literal
new Intl.*(locales, options), Intl.*(...), supportedLocalesOf, Intl.getCanonicalLocalesa malformed locale tag; a time zone, unit or currency code that doesn't exist; digits out of rangetags and options written in the code, the platform's own (navigator.language, formatter.resolvedOptions().timeZone)
toLocaleString(locales, options) (numbers, bigints, dates, arrays, typed arrays, Temporal), toLocaleDateString, localeCompare, toLocaleUpperCasethe samethe same
formatter.format(date) (Intl.DateTimeFormat)an invalid datea date that isn't parsed from text, a number
Uint8Array.fromBase64(text), fromHex, setFromBase64, Intl.DisplayNames#of, Temporal.*.from(text) and the other Temporal memberstext that doesn't parse, a code or field out of rangearguments written in the code
eval(text), new Function(...)text that isn't codetext written in the code

An operator ​

Bigint / and % (also /=, %=) can't fail when the divisor is known not to be 0n: a literal other than 0n, or checked (if (d === 0n) return ...;, d > 0n && ...). ** can't fail when the exponent is known not to be negative (2n ** 8n, if (e < 0n) return ...;). An operand is a bigint when its type says so (a literal, a declared bigint, a field declared bigint in another file). Numbers don't throw: 1 / 0 is Infinity.

What to write ​

The message says what fails and what to write instead:

error[unhandled-failure]: `prices.reduce()` can throw, but the failure is not handled: without an initial value, `reduce` throws a `TypeError` on an empty list, and `prices` isn't known to have an element
  = help: Pass an initial value (`prices.reduce(f, initial)`), or check `prices.length > 0` first. Or wrap it: `unsafe(() => ...)` returns a Result you must check
✕ Rejectedunhandled-failure
ts
export function total(prices: readonly number[]): number {
  return prices.reduce((a, b) => a + b);
}

export function stamp(input: string): string {
  return new Date(input).toISOString();
}

export function money(amount: number, digits: number): string {
  return amount.toFixed(digits);
}

✅ Accepted: the forms that can't fail

✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";

export type StampError = Enum<{ NotADate: { input: string } }>;
export const StampError = constructors<StampError>();

export function total(prices: readonly number[]): number {
  return prices.reduce((a, b) => a + b, 0);
}

export function stamp(input: string): Result<string, StampError> {
  const date = new Date(input);
  if (Number.isNaN(date.getTime())) return err(StampError.NotADate({ input }));
  return date.toISOString();
}

export function money(amount: number, digits: number): string {
  if (digits < 0 || digits > 100) return amount.toFixed(2);
  return amount.toFixed(digits);
}

export function label(text: string, width: number): string {
  return text.padStart(width);
}
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";

export type StampError = Enum<{ NotADate: { input: string } }>;
export const StampError = constructors<StampError>();

export function total(prices: readonly number[]): number {
  return prices.reduce((a, b) => a + b, 0);
}

export function stamp(input: string): Result<string, StampError> {
  const date = new Date(input);
  if (Number.isNaN(date.getTime())) return err(({ tag: "NotADate", input } satisfies StampError as StampError));
  return date.toISOString();
}

export function money(amount: number, digits: number): string {
  if (digits < 0 || digits > 100) return amount.toFixed(2);
  return amount.toFixed(digits);
}

export function label(text: string, width: number): string {
  return text.padStart(width);
}

A locale or time zone from data is checked once, where it enters the program: the formatter it makes is reused, and can't fail any more.

✓ Accepted0 diagnostics
ts
import { isErr, type Result, unsafe } from "@evobug_com/safe-ts-std/result";

const FALLBACK = new Intl.DateTimeFormat("en-GB", { timeZone: "UTC" });

export function formatterFor(locale: string, timeZone: string): Intl.DateTimeFormat {
  const made: Result<Intl.DateTimeFormat, unknown> = unsafe(() => new Intl.DateTimeFormat(locale, { timeZone }));
  return isErr(made) ? FALLBACK : made;
}

export function share(total: bigint, parts: bigint): bigint {
  return parts === 0n ? 0n : total / parts;
}

No std helper is needed for these: each has a built-in form that can't fail (an initial value, Number.isNaN(date.getTime()), padStart, a check of the divisor), and a locale or time zone is validated by making the formatter in unsafe(...). The only quick fix is the usual wrap in unsafe(() => ...): an initial value for reduce depends on what the reduction means, so it isn't mechanical.

What isn't reported, and why ​

These were reported at first, and narrowed after reading what they found in an adopter's working code, where every one of them was a value in range for a reason the checker can't see:

  • A typed array's or buffer's length (new Uint8Array(n), new ArrayBuffer(n), buffer.resize(n)) and target.set(source, offset): 161 and 23 findings, every length a size computed from dimensions, every offset kept within the target by construction. They throw for a negative length or a source that doesn't fit; the map says so, and they aren't reported.
  • A date made from a number that isn't parsed from text (new Date(ms), new Date(this.now()), formatter.format(ms)) or made where the code doesn't see (a Date parameter or field, what a package returns): 17 findings, all of them times from a clock. new Date(NaN) and times past ±8.64e15 ms from such a number still throw in toISOString. Measured again later (the adopter, about 760 files, and this repository's examples), by where the date comes from: of the 5 toISOString receivers and 3 format(date) arguments not judged, 1 is new Date(Date.now() + days * 86_400_000) (a valid time plus arithmetic), 2 are new Date(ms) of a number parameter, 1 of a number field, 1 is a Date property, and the 3 arguments are a parameter, a destructured binding and a ?:; every one a time from a clock. What decides these is who made the number or the date, which a brand on the value could say and a rule reading the function can't: a parameter or a field isn't reported, and a number parsed from text is number-parse-nan's (and this check's, above). The same for toTemporalInstant and Intl.DateTimeFormat's format, formatToParts, formatRange and formatRangeToParts.
  • A DataView kept in a field, or over a buffer whose length the function reads: 37 findings, every read guarded by a cursor check in a helper (this.need(4)), which the checker doesn't follow; a view made over a buffer whose length nothing reads is still reported.
  • An argument the function computes itself: a count from a roll (2 + Math.floor(roll() * 3)), a table of constants, a callback's index. Only arguments that come from data, as defined above, are reported.

Atomics.wait also throws on a browser's main thread whatever its arguments; that isn't seen.

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