Examples
report
What throws without saying so: a report built with JSON.parse, a pattern, a bigint division and a template, against its conforming version.
These are the sources of the example, as they are at the commit this site was built from: classic is what tsc --strict accepts, strict what conforms. Examples says what each is refused for, and each is a scenario of the playground, where it can be changed.
#classic/report.ts
// "Classic" TypeScript: `tsc --strict` accepts all of it, and each function can throw without its type saying so.
export interface Sale {
product: string;
cents: bigint;
tags: unknown[];
}
// Throws a SyntaxError on text that is not JSON.
export function readSales(json: string): Sale[] {
return JSON.parse(json);
}
// Throws a SyntaxError on a pattern that is not valid: "(" for instance.
export function matching(sales: Sale[], pattern: string): Sale[] {
const wanted = new RegExp(pattern, "i");
return sales.filter((sale) => wanted.test(sale.product));
}
// Throws a RangeError when there is no sale: a bigint cannot be divided by zero.
export function average(sales: Sale[]): bigint {
const total = sales.reduce((sum, sale) => sum + sale.cents, 0n);
return total / BigInt(sales.length);
}
// Throws a RangeError when `digits` is above 100.
export function euros(cents: bigint, digits: number): string {
return (Number(cents) / 100).toFixed(digits);
}
// Throws a TypeError on a tag that does not convert to text: a symbol, an object without a prototype.
export function line(sale: Sale): string {
return `${sale.product}: ${euros(sale.cents, 2)} [${sale.tags}]`;
}
export function report(json: string, pattern: string): string {
const sales = matching(readSales(json), pattern);
return [...sales.map(line), `average: ${euros(average(sales), 2)}`].join("\n");
}#classic/strict-ts.json
{}#strict/report.ts
// The same report, conforming: each failure is in a type, and nothing else can throw.
import { quotient, Result, s, textOf } from "@strict-ts/std";
import { fixed, parseJson, pattern, whole } from "./unsafe/system.js";
const Sale = s.object({ product: s.string, cents: s.integer(s.number), tags: s.array(s.string) });
export type Sale = s.Infer<typeof Sale>;
export const readSales = (json: string) => parseJson(json).andThen(s.array(Sale).parse).mapErr(textOf);
export const matching = (sales: readonly Sale[], source: string) =>
pattern(source).map((wanted) => sales.filter((sale) => wanted.test(sale.product)));
/** `BigInt(1.5)` throws, and so does a division by zero: both are in the type. */
export const average = (sales: readonly Sale[]) =>
Result.gen(function* () {
const total = yield* whole(sales.reduce((sum, sale) => sum + sale.cents, 0));
const count = yield* whole(sales.length);
return quotient(total, count).okOr("no sale matches");
});
export const euros = (cents: number) => fixed(cents / 100, 2);
export const line = (sale: Sale) => euros(sale.cents).map((amount) => `${sale.product}: ${amount} [${sale.tags.join(", ")}]`);
export const report = (json: string, source: string) =>
Result.gen(function* () {
const sales = yield* matching(yield* readSales(json), source);
const lines: readonly string[] = yield* all(sales.map(line));
const mean = yield* average(sales);
return Result.ok([...lines, `average: ${yield* euros(Number(mean))}`].join("\n"));
});
/** Every value, or the first error. */
const all = <T, E>(results: readonly Result<T, E>[]): Result<readonly T[], E> =>
results.reduce<Result<readonly T[], E>>((sum, result) => sum.andThen((values) => result.map((value) => [...values, value])), Result.ok([]));#strict/strict-ts.json
{
"unsafeDirs": ["unsafe"]
}#strict/unsafe/system.ts
import { attempt, textOf } from "@strict-ts/std";
// What may throw is called here, and leaves as a Result.
export const parseJson = (text: string) => attempt((): unknown => JSON.parse(text), textOf);
export const pattern = (source: string) => attempt(() => new RegExp(source, "i"), textOf);
export const fixed = (value: number, digits: number) => attempt(() => value.toFixed(digits), textOf);
export const whole = (value: number) => attempt(() => BigInt(value), textOf);