failure-contract
A function that can propagate a PropagateError put into a slot that doesn't declare it. A slot is a place whose callers can't see what fills it: a member of an interface or of an object type, an abstract method, a method a subclass overrides, the type of a callback kept for later (a parameter, a field, the items of a collection). On by default, as an error.
Why: the checker knows what a call propagates by following it into the function it runs. A call through a slot (store.get(id) with store: Store, task.run() with task: Task, job() for a callback taken from a list) runs whatever was put there, so there is nothing to follow: the slot's type is all the caller has. Like a trait method's signature in Rust, the type says whether it can fail. std's Throws<R, E> (R to TypeScript) says the function may throw the PropagateErrors E; a function type without it can't fail. A call through a slot propagates what the slot declares, and whatever goes into the slot is checked against it here. Without the check, an implementation's failure reaches callers that were never asked to handle it, and nothing reports it. Guides: Errors.
❌ Rejected: the store fails, and the interface says it can't
✕ Rejectedfailure-contract
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
export class NotFound extends PropagateError {}
export interface Documents {
readonly load: (id: string) => string;
}
export class FileDocuments implements Documents {
load(id: string): string {
if (id === "") throw new NotFound("no id");
return `document ${id}`;
}
}✅ Accepted: the interface declares the failure, and the code that calls through it handles it
✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, PropagateError, type Result, type Throws } from "@evobug_com/safe-ts-std/result";
export class NotFound extends PropagateError {}
export interface Documents {
readonly load: (id: string) => Throws<string, NotFound>;
}
export class FileDocuments implements Documents {
load(id: string): string {
if (id === "") throw new NotFound("no id");
return `document ${id}`;
}
}
export type OpenError = Enum<{ Missing: { id: string } }>;
export const OpenError = constructors<OpenError>();
export function open(documents: Documents, id: string): Result<string, OpenError> {
try {
return documents.load(id);
} catch (error) {
if (error instanceof NotFound) return err(OpenError.Missing({ id }));
throw error;
}
}ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, PropagateError, type Result, type Throws } from "@evobug_com/safe-ts-std/result";
export class NotFound extends PropagateError {}
export interface Documents {
readonly load: (id: string) => Throws<string, NotFound>;
}
export class FileDocuments implements Documents {
load(id: string): string {
if (id === "") throw new NotFound("no id");
return `document ${id}`;
}
}
export type OpenError = Enum<{ Missing: { id: string } }>;
export const OpenError = constructors<OpenError>();
export function open(documents: Documents, id: string): Result<string, OpenError> {
try {
return documents.load(id);
} catch (error) {
if (error instanceof NotFound) return err(({ tag: "Missing", id } satisfies OpenError as OpenError));
throw error;
}
}✅ Also accepted: the implementation handles its failure itself, and the slot stays one that can't fail
✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
export class NotFound extends PropagateError {}
export interface Documents {
readonly load: (id: string) => string;
}
function read(id: string): string {
if (id === "") throw new NotFound("no id");
return `document ${id}`;
}
export class CachedDocuments implements Documents {
load(id: string): string {
try {
return read(id);
} catch (error) {
if (error instanceof NotFound) return "";
throw error;
}
}
}The message says both ways out: catch the failure where it is put into the slot, or declare it on the slot (Throws<string, NotFound> as the member's return type). A kind counts as declared when it is one the slot names or a subclass of one; Throws<R, PropagateError> declares every kind, Throws<R, never> none. Every implementation then fails with at most what the slot declares, so a caller that handles that handles every one.
What goes into a slot
- A class that
implementsan interface, member by member: each method (declared in the class or inherited) against the member it implements, also members of the interfaces it extends. Reported at the method. - An object literal annotated with an interface or an object type (
const store: Store = { ... }), passed where one is expected, returned from a function declared to return one, assigned to a field declared with one, or pushed into a collection of them: each member that is a function, written in place or by name ({ get: find }). Reported at the member. - A value whose class is visible, put where an interface is expected without the class saying
implementsit:new C(),this, a local or parameter declaredC, a field declared withC, a call of a function declared to returnC. Reported at the value. - An override against the method it overrides, whatever the base declares or (with no
Throws) what its body lets out; an abstract method's implementation against the abstract method, which declares nothing unless it saysThrows. - A function's own return type:
function find(id: string): Throws<string, NotFound>is a claim, and its body is checked against it. Callers get what it declares. - A callback kept for later where its type is written: handed to a function of yours that doesn't call it right away (it stores it, or calls it in a timer), as a parameter declared with a function type; put into a collection whose items are a function type (
jobs.push(job)withjobs: Job[]); assigned to a field or a member declared with one, also anon...member of a type the project declares (port.onmessage = handle, where a platform object'sworker.onmessageis the runtime's entry point and staysuncaught-propagation). Reported at the function used by name, or at what fails inside the function written in place: the name and the arrow that calls it get the same finding, once.
❌ Rejected: the override fails where the method it overrides can't
✕ Rejectedfailure-contract
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
export class Offline extends PropagateError {}
export class Clock {
now(): number {
return 0;
}
}
export class NetworkClock extends Clock {
private readonly connected = false;
override now(): number {
if (!this.connected) throw new Offline("no time server");
return 1;
}
}A stored callback declared with Throwing<Args, R, E> (std's (...args: Args) => Throws<R, E>) may fail with what it declares: it is allowed where it is handed over, and the call that runs it later propagates what the type declares, so that call is where it is handled.
✅ Accepted: the queue's jobs may fail with Rejected, and the loop that runs them handles it
✓ Accepted0 diagnostics
ts
import { PropagateError, type Throwing } from "@evobug_com/safe-ts-std/result";
export class Rejected extends PropagateError {}
type Job = Throwing<[id: string], void, Rejected>;
export class Queue {
private readonly jobs: Job[] = [];
add(job: Job): void {
this.jobs.push(job);
}
/** Runs every job; returns how many were rejected. */
drain(id: string): number {
let rejected = 0;
for (const job of this.jobs) {
try {
job(id);
} catch (error) {
if (!(error instanceof Rejected)) throw error;
rejected += 1;
}
}
return rejected;
}
}
function charge(id: string): void {
if (id === "") throw new Rejected("no customer");
}
export function billing(): Queue {
const queue = new Queue();
queue.add(charge);
return queue;
}❌ Rejected: the same queue, a job failing with more than Job declares
✕ Rejectedfailure-contract
ts
import { PropagateError, type Throwing } from "@evobug_com/safe-ts-std/result";
export class Rejected extends PropagateError {}
export class Offline extends PropagateError {}
type Job = Throwing<[id: string], void, Rejected>;
export class Queue {
private readonly jobs: Job[] = [];
add(job: Job): void {
this.jobs.push(job);
}
}
function sync(id: string): void {
if (id === "") throw new Offline("no network");
}
export function syncing(): Queue {
const queue = new Queue();
queue.add(sync);
return queue;
}Calls through a slot
A call through a slot propagates what it declares, as a call of a function that throws it would. The function type written for the value called is the contract, however the call reaches the value: store.get(id) with store: Store, deps.store.get(id), a member taken off one (const { get } = store), job() with job: Job (also a module-level const job: Job), an item of a declared collection (for (const job of jobs) job(), jobs.forEach((job) => job()), jobs[0]?.(), jobs[i]?.(), jobs.at(-1)?.()), a value of a Record<string, Job> or of an index signature (table.a?.(), table[name]?.(), and a local taken out by the key and checked: const job = table[name]; if (job !== undefined) job()), a Map's value (byName.get(name)?.(), also kept in a local first), a tuple's item (pair[0]()), a computed key of an object type whose members all have the same type (table[key]() with table: { a: Job; b: Job }), a field declared with a function type (this.onDone()). The type is read through aliases, generic aliases and Readonly, Partial, Required, Pick, Omit, NonNullable. A plain function type declares nothing, so a call through it propagates nothing: what was put in was checked against it. What reaches the top of the program is uncaught-propagation, a rejection nobody awaits floating-rejection, at the same places as for a direct call.
A method called on an item of a collection of a class (for (const task of tasks) task.run() with tasks: readonly Task[]) is that class's method; an override is held to it by the rule.
Async slots
What an async slot rejects with is written inside its promise: Promise<Throws<T, E>>. Throws<Promise<T>, E> means the same, so Throwing<[id: string], Promise<User>, NotFound> is an async callback that rejects with NotFound. A call through it is a rejection: awaited inside a try, it is caught there; not awaited, it is a floating-rejection. An implementation that throws before its first await is held to the same declaration.
✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, PropagateError, type Result, type Throws } from "@evobug_com/safe-ts-std/result";
export class Offline extends PropagateError {}
export interface Api {
readonly profile: (id: string) => Promise<Throws<string, Offline>>;
}
export type ProfileError = Enum<{ Unreachable: {} }>;
export const ProfileError = constructors<ProfileError>();
export async function profileOf(api: Api, id: string): Promise<Result<string, ProfileError>> {
try {
return await api.profile(id);
} catch (error) {
if (error instanceof Offline) return err(ProfileError.Unreachable());
throw error;
}
}ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, PropagateError, type Result, type Throws } from "@evobug_com/safe-ts-std/result";
export class Offline extends PropagateError {}
export interface Api {
readonly profile: (id: string) => Promise<Throws<string, Offline>>;
}
export type ProfileError = Enum<{ Unreachable: {} }>;
export const ProfileError = constructors<ProfileError>();
export async function profileOf(api: Api, id: string): Promise<Result<string, ProfileError>> {
try {
return await api.profile(id);
} catch (error) {
if (error instanceof Offline) return err(({ tag: "Unreachable" } satisfies ProfileError as ProfileError));
throw error;
}
}Through a type alias
The declaration may be written once as a type alias and named wherever it is needed, in a member's type, a method's, a callback parameter's, a function's own return type or an abstract method's: type Reply<T> = Promise<Throws<T, Offline>>, then (id: string) => Reply<string>. The alias is read here or imported (also as api.Reply<string>), through an alias of it (type Answer<T> = Reply<T>), with its type arguments (type Fails<T, E> = Throws<T, E>, then Fails<string, Offline> declares Offline) and its defaults. An alias that doesn't stand for a Throws (type Plain<T> = Promise<T>) declares nothing, as the type it names would.
✓ Accepted0 diagnostics
ts
import { PropagateError, type Throws } from "@evobug_com/safe-ts-std/result";
export class Offline extends PropagateError {}
type Reply<T> = Promise<Throws<T, Offline>>;
interface Route {
readonly path: string;
readonly run: (id: number) => Reply<string>;
}
export const routes: readonly Route[] = [
{
path: "/profile",
run: async (id) => {
if (id < 0) throw new Offline("no connection");
return `profile ${id}`;
},
},
];Where inference stays
Declarations are needed only where inference ends. A callback a function of yours calls right away (apply((id) => find(id))) is followed into it, declared or not: what it throws reaches the caller of apply. So is a const holding a function (const pick: Picker = (x) => ...), a field's initializer that is a function, written in place or by name (handler = find; where the field's type declares failures with Throws, either is held to it), and a module-level object's method called on that object (api.load(id)); where such a value is handed on, it is checked there.
Quick fix
None: which way out is right (catch where it fails, or widen the slot and handle it at the callers) is the author's choice. The help writes the declaration that would admit the failure.
What the rule can't see
Where what goes into a slot can't be known when it goes in, nothing is checked:
- A value of an inferred type.
use(makeRepo())wheremakeRepodeclares no return type,const repo = pick(flag); use(repo): the class isn't written down, so its methods aren't checked againstLoader. Declare the return type. - A value from a package, and a slot a package declares. A package's class passed where your interface is expected, or your class implementing a package's interface (
class Plugin implements VitePlugin): the package's types aren't read. - A class put where an unrelated class is expected (
use(b)withuse(clock: Clock)andbof a class that doesn't extendClock, which TypeScript accepts by shape): only subclasses are checked, through their overrides. - A value whose type isn't written, or is computed: a call through a value of an inferred type, or of a mapped or conditional type (
Lazy<{ a: Job }>withtype Lazy<T> = { [K in keyof T]: T[K] }), is unknown and propagates nothing; so is a computed key of an object type whose members have different types (table[key]()withtable: { a: Job; b: Plain }), where the key's own type isn't read. What is put into aRecord, an index signature, aMapor aSetis checked: an object literal put where aRecord<string, Job>is expected (each value againstJob), anew Map([["a", find]])ornew Set([find])where aMap<K, Job>,ReadonlyMaporSetis expected. A slot type written throughPartial,Readonly,Required,Pick,Omit,NonNullableor a generic alias given its argument (Hooks<Plain>withtype Hooks<F> = { onload: F }) is the type it stands for. - A callback whose type isn't written where it is kept: a parameter without an annotation, a collection whose binding has no annotation (
const seen = new Set<Handler>(); writeconst seen: Set<Handler> = new Set()). A callback kept there is stilluncaught-propagation. - A field set from outside the class to something other than a function or an object written there:
this.load = options.loadwithoptionsof an inferred type. - A generic
E:Throws<T, E>withEa type parameter declares a kind namedEonly. - Static methods are not checked against the static method they override.
- What inference itself can't see in an implementation (a method of an interface-typed value it calls, a callback stored in an object literal written inside a function and called through it): it isn't counted against the slot either. See
uncaught-propagation, "What the rule can't see".