Examples
cart
Explicit mutability: a cart that changes what it is given, against a version whose types say what may change.
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/cart.ts
// "Classic" TypeScript: nothing in a signature says what a function changes.
export interface Item {
name: string;
cents: number;
quantity: number;
}
export interface Cart {
items: Item[];
coupon?: string;
}
let lastCart: Cart = { items: [] };
// Changes the cart it is given, and remembers it for everyone.
export function add(cart: Cart, item: Item): Cart {
cart.items.push(item);
lastCart = cart;
return cart;
}
// Sorts the caller's array in place: the caller's own order is gone.
export function cheapestFirst(items: Item[]): Item[] {
return items.sort((a, b) => a.cents - b.cents);
}
// Reads the clock: the same call gives another answer tomorrow.
export function total(cart: Cart): number {
const sum = cart.items.reduce((cents, item) => cents + item.cents * item.quantity, 0);
return new Date().getDay() === 5 ? sum * 0.9 : sum;
}
export function applyCoupon(cart: Cart, coupon: string): void {
cart.coupon = coupon;
for (const item of cart.items) item.cents = Math.round(item.cents * 0.95);
}
export const previous = (): Cart => lastCart;#classic/strict-ts.json
{}#strict/strict-ts.json
{
"unsafeDirs": ["unsafe"],
"pureDirs": ["domain"]
}#strict/domain/cart.ts
// The same cart, conforming. Its directory is declared pure: no clock, no shared state, and a signature says what
// a function changes.
import type { Mut } from "@strict-ts/std";
export interface Item {
readonly name: string;
readonly cents: number;
readonly quantity: number;
}
export interface Cart {
readonly items: readonly Item[];
readonly coupon?: string;
}
export const empty: Cart = { items: [] };
/** A new cart: the one it was given is as it was. */
export const add = (cart: Cart, item: Item): Cart => ({ ...cart, items: [...cart.items, item] });
/** A sorted copy. */
export const cheapestFirst = (items: readonly Item[]): readonly Item[] => [...items].sort((a, b) => a.cents - b.cents);
/** The day is an argument: the same call always gives the same answer. */
export const total = (cart: Cart, day: number): number => {
const sum = cart.items.reduce((cents, item) => cents + item.cents * item.quantity, 0);
return day === 5 ? sum * 0.9 : sum;
};
export const applyCoupon = (cart: Cart, coupon: string): Cart => ({
coupon,
items: cart.items.map((item) => ({ ...item, cents: Math.round(item.cents * 0.95) })),
});
/** Where changing in place is wanted, the signature asks for it: Rust's `&mut`. */
export function restock(counts: Mut<Map<string, number>>, item: Item): void {
counts.set(item.name, (counts.get(item.name) ?? 0) + item.quantity);
}