Examples
invoice
The invoice challenge: classic TypeScript against its conforming version written with @strict-ts/std.
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/invoice.ts
// Challenge: "classic" TypeScript, which compiles with tsc --strict.
// Make it conform to strict-ts (0 errors) without breaking its behaviour.
import { randomUUID } from "node:crypto";
type Status = "draft" | "sent" | "paid" | "cancelled";
interface Line {
label: string;
quantity: number;
unitPrice: number;
}
export interface Invoice {
id: string;
customer: string;
lines: Line[];
status: Status;
paidAt: Date | null;
}
export function createInvoice(customer: string, lines: Line[]): Invoice {
if (lines.length === 0) throw new Error("An invoice must have at least one line");
return { id: randomUUID(), customer, lines, status: "draft", paidAt: null };
}
export function total(invoice: Invoice): number {
return invoice.lines.reduce((sum, l) => sum + l.quantity * l.unitPrice, 0);
}
export function parseInvoice(json: string): Invoice {
return JSON.parse(json) as Invoice;
}
export function firstLine(invoice: Invoice): Line {
return invoice.lines[0]!;
}
export function statusLabel(status: Status): string {
switch (status) {
case "draft":
return "Draft";
case "sent":
return "Sent";
case "paid":
return "Paid";
}
return "?";
}
export async function sendReminder(invoice: Invoice): Promise<void> {
console.log(`Reminder sent to ${invoice.customer} (${total(invoice)} €)`);
}
export function remindUnpaid(invoices: Invoice[]): void {
for (const invoice of invoices) {
if (invoice.status === "sent") sendReminder(invoice);
}
}#classic/strict-ts.json
{}#derived/invoice.schema.ts
// Generated by strict-ts-derive from invoice.ts. Do not edit: change the types, and generate again.
// Each schema is annotated with its type: the compiler refuses one that does not produce it.
import { s } from '@strict-ts/std';
import type { Invoice, Line } from "./invoice.js";
export const LineSchema: s.Schema<Line> = s.object({
label: s.string,
quantity: s.number,
unitPrice: s.number,
});
export const InvoiceSchema: s.Schema<Invoice> = s.object({
id: s.string,
customer: s.string,
status: s.literal("draft", "sent", "paid", "cancelled"),
lines: s.array(LineSchema),
paidAt: s.optional(s.date),
});#derived/invoice.ts
// The same solution with the types written as types: their schemas are generated (invoice.schema.ts).
import { err, Option } from "@strict-ts/std";
import { InvoiceSchema } from "./invoice.schema.js";
import { newId, parseJson } from "./unsafe/system.js";
export type Line = { readonly label: string; readonly quantity: number; readonly unitPrice: number };
export type Invoice = {
readonly id: string;
readonly customer: string;
readonly status: "draft" | "sent" | "paid" | "cancelled";
readonly lines: readonly Line[];
readonly paidAt?: Date;
};
export const createInvoice = (customer: string, lines: readonly Line[]) =>
lines.length === 0 ? err("no-lines") : newId().map((id): Invoice => ({ id, customer, lines, status: "draft" }));
export const total = (invoice: Invoice) => invoice.lines.reduce((sum, l) => sum + l.quantity * l.unitPrice, 0);
export const parseInvoice = (json: string) => parseJson(json).andThen(InvoiceSchema.parse);
export const firstLine = (invoice: Invoice) => Option.from(invoice.lines[0]);
const labels = { draft: "Draft", sent: "Sent", paid: "Paid", cancelled: "Cancelled" } satisfies Readonly<Record<Invoice["status"], string>>;
export const statusLabel = (status: Invoice["status"]) => labels[status];
export async function sendReminder(invoice: Invoice): Promise<void> {
console.log(`Reminder sent to ${invoice.customer} (${total(invoice)} €)`);
}
export async function remindUnpaid(invoices: readonly Invoice[]): Promise<void> {
for (const invoice of invoices) if (invoice.status === "sent") await sendReminder(invoice);
}#derived/strict-ts.json
{
"unsafeDirs": ["unsafe"]
}#derived/unsafe/system.ts
import { randomUUID } from "node:crypto";
import { attempt } from "@strict-ts/std";
export const newId = () => attempt(() => randomUUID(), String);
export const parseJson = (text: string) => attempt((): unknown => JSON.parse(text), String);#strict/invoice.ts
// Concise solution (@strict-ts/std): Result with methods, schemas, `satisfies` object.
import { err, Option, s } from "@strict-ts/std";
import { newId, parseJson } from "./unsafe/system.js";
const Line = s.object({ label: s.string, quantity: s.number, unitPrice: s.number });
const Invoice = s.object({
id: s.string,
customer: s.string,
status: s.literal("draft", "sent", "paid", "cancelled"),
lines: s.array(Line),
paidAt: s.optional(s.date),
});
type Line = s.Infer<typeof Line>;
export type Invoice = s.Infer<typeof Invoice>;
export const createInvoice = (customer: string, lines: readonly Line[]) =>
lines.length === 0 ? err("no-lines") : newId().map((id): Invoice => ({ id, customer, lines, status: "draft" }));
export const total = (invoice: Invoice) => invoice.lines.reduce((sum, l) => sum + l.quantity * l.unitPrice, 0);
export const parseInvoice = (json: string) => parseJson(json).andThen(Invoice.parse);
export const firstLine = (invoice: Invoice) => Option.from(invoice.lines[0]);
const labels = { draft: "Draft", sent: "Sent", paid: "Paid", cancelled: "Cancelled" } satisfies Readonly<Record<Invoice["status"], string>>;
export const statusLabel = (status: Invoice["status"]) => labels[status];
export async function sendReminder(invoice: Invoice): Promise<void> {
console.log(`Reminder sent to ${invoice.customer} (${total(invoice)} €)`);
}
export async function remindUnpaid(invoices: readonly Invoice[]): Promise<void> {
for (const invoice of invoices) if (invoice.status === "sent") await sendReminder(invoice);
}#strict/strict-ts.json
{
"unsafeDirs": ["unsafe"]
}#strict/unsafe/system.ts
import { randomUUID } from "node:crypto";
import { attempt } from "@strict-ts/std";
export const newId = () => attempt(() => randomUUID(), String);
export const parseJson = (text: string) => attempt((): unknown => JSON.parse(text), String);