Enums and match
When a value belongs to a closed set of cases—each carrying its own payload—model it with Enum<{ ... }> and branch on it with match. Adding a new variant later turns every unhandled branch into a compile error instead of a silent runtime bug.
In short
- Declare variants with
Enum<{ ... }>and build them viaconstructors<T>(). - Branch exhaustively with
match(value, { ... }): forget a variant and TypeScript refuses to compile; the build turnsmatchinto a flatswitch. - Single-variant checks: use
is(...),variant(...), or a wildcard_arm. Option<T>support: handleundefineddirectly inmatchor cover it with_.- No TypeScript
enum: use string unions ("red" | "green") for plain tags—matchworks on string unions too. - Closed-set
if/?:chains: cover every member or terminate withunreachable(x).
Describe the kinds, handle each one
Enum<...> lists the variants and their data. constructors gives you a function to build each one, under the same name as the type:
✓ Accepted0 diagnostics
ts
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
export type Shape = Enum<{
Circle: { radius: number };
Rect: { width: number; height: number };
Empty: {};
}>;
export const Shape = constructors<Shape>();
export const unit = Shape.Circle({ radius: 1 });
export function area(shape: Shape): number {
return match(shape, {
Circle: ({ radius }) => Math.PI * radius ** 2,
Rect: ({ width, height }) => width * height,
Empty: () => 0,
});
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
export type Shape = Enum<{
Circle: { radius: number };
Rect: { width: number; height: number };
Empty: {};
}>;
export const Shape = constructors<Shape>();
export const unit = ({ tag: "Circle", radius: 1 } satisfies Shape as Shape);
export function area(shape: Shape): number {
{ const __ms1 = shape; let __mv1: number; switch (__ms1.tag) {
case "Circle": { const { radius } = __ms1; __mv1 = Math.PI * radius ** 2; break; }
case "Rect": { const { width, height } = __ms1; __mv1 = width * height; break; }
case "Empty": { __mv1 = 0; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}match needs a handler for every variant. When someone adds a Triangle later, every match without one stops compiling: you get a list of places to update, not a bug in production. Each handler gets just that variant's data, with its types.
Enums can also take type parameters and contain themselves, like this tree:
✓ Accepted0 diagnostics
ts
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
export type Tree<T> = Enum<{
Leaf: { value: T };
Node: { left: Tree<T>; right: Tree<T> };
}>;
export function sum(tree: Tree<number>): number {
return match(tree, {
Leaf: ({ value }) => value,
Node: ({ left, right }) => sum(left) + sum(right),
});
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
export type Tree<T> = Enum<{
Leaf: { value: T };
Node: { left: Tree<T>; right: Tree<T> };
}>;
export function sum(tree: Tree<number>): number {
{ const __ms1 = tree; let __mv1: number; switch (__ms1.tag) {
case "Leaf": { const { value } = __ms1; __mv1 = value; break; }
case "Node": { const { left, right } = __ms1; __mv1 = sum(left) + sum(right); break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}The build turns match into a plain switch, so it's as fast as writing one yourself.
The result type
Without an expected type, match returns the union of what the handlers return. With one (a declared variable or return type, a typed argument), the handlers are checked against it. So literals keep their type, and you don't need to annotate each handler:
✓ Accepted0 diagnostics
ts
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
type Response = Enum<{ Ok: { body: string }; Timeout: {}; Refused: { code: number } }>;
type Level = "info" | "error";
export function level(response: Response): Level {
return match(response, {
Ok: () => "info",
Timeout: () => "error",
Refused: () => "error",
});
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
type Response = Enum<{ Ok: { body: string }; Timeout: {}; Refused: { code: number } }>;
type Level = "info" | "error";
export function level(response: Response): Level {
{ const __ms1 = response; let __mv1: Level; switch (__ms1.tag) {
case "Ok": { __mv1 = "info"; break; }
case "Timeout": { __mv1 = "error"; break; }
case "Refused": { __mv1 = "error"; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}A handler that returns something else, such as "warning", is a compile error at that handler.
Building values
A value is a plain object with a tag: { tag: "Circle", radius: 1 }. Constructors write the tag for you. You need the const Shape = constructors<Shape>() line because a type exists only for the compiler: until you declare a value, there is nothing to call.
✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
export type Shape = Enum<{
Circle: { radius: number };
Rect: { width: number; height: number };
Empty: {};
}>;
export const Shape = constructors<Shape>();
export const unit = Shape.Circle({ radius: 1 });
export const nothing = Shape.Empty();
export function square(side: number): Shape {
return Shape.Rect({ width: side, height: side });
}ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
export type Shape = Enum<{
Circle: { radius: number };
Rect: { width: number; height: number };
Empty: {};
}>;
export const Shape = constructors<Shape>();
export const unit = ({ tag: "Circle", radius: 1 } satisfies Shape as Shape);
export const nothing = ({ tag: "Empty" } satisfies Shape as Shape);
export function square(side: number): Shape {
return ({ tag: "Rect", width: side, height: side } satisfies Shape as Shape);
}Each constructor takes exactly its variant's data, or nothing for a variant without data. Importing Shape gives other modules both the type and the constructors. The build turns each call into the plain object, so constructors cost nothing. Variant names can be lowercase too (Cursor.move({ x, y })).
The build leaves a call to the runtime constructor in a few cases: a constructor passed as a function (points.map(Shape.Circle)), an optional call, or more than one argument. safe-ts explain lists each one with the reason. Write points.map((p) => Shape.Circle(p)) to get the plain object.
If you write Shape.Circle(...) before declaring the constructors, the checker says so and offers to add the line. You don't need constructors for enums you only match on, such as data from parseJson.
Constructors for a generic enum
Declare them for each type argument: const NumberTree = constructors<Tree<number>>().
Methods on an enum
An enum can declare methods, called on its values like Rust's impl UploadError { fn describe(&self) ... }. Declare them as the second argument of Enum, and write them on its table with .impl({...}), each taking the value first:
✓ Accepted0 diagnostics
ts
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
export type CheckError = Enum<
{ TooBig: { size: number }; BadType: { mime: string } },
{ readonly describe: () => string }
>;
export const CheckError = constructors<CheckError>().impl({
describe: (error) =>
match(error, { TooBig: ({ size }) => `too big (${size} bytes)`, BadType: ({ mime }) => `type ${mime} is not allowed` }),
});
export type UploadError = Enum<
{ Invalid: { problem: CheckError }; Retrying: { attempt: number }; StoreFull: {} },
{
readonly describe: () => string;
/** The next state after a failed attempt: retry until `MAX_ATTEMPTS`, then give up. */
readonly nextAttempt: () => UploadError;
}
>;
export const UploadError = constructors<UploadError>().impl({
MAX_ATTEMPTS: 3,
describe: (error) =>
match(error, {
Invalid: ({ problem }) => `invalid: ${problem.describe()}`,
Retrying: ({ attempt }) => `retrying (attempt ${attempt})`,
StoreFull: () => "the store is full",
}),
nextAttempt: (error): UploadError =>
match(error, {
Retrying: ({ attempt }) =>
attempt >= UploadError.MAX_ATTEMPTS ? UploadError.StoreFull() : UploadError.Retrying({ attempt: attempt + 1 }),
_: () => UploadError.Retrying({ attempt: 1 }),
}),
});
export function messages(errors: readonly UploadError[]): string[] {
return errors.map((error) => error.nextAttempt().describe());
}ts
import type { Data as __EnumData } from "@evobug_com/safe-ts-std/enum"; import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
export type CheckError = Enum<
{ TooBig: { size: number }; BadType: { mime: string } },
{ readonly describe: () => string }
>;
export const CheckError = constructors<CheckError>().impl({
describe: (error): string =>
match(error, { TooBig: ({ size }) => `too big (${size} bytes)`, BadType: ({ mime }) => `type ${mime} is not allowed` }),
});
export type UploadError = Enum<
{ Invalid: { problem: CheckError }; Retrying: { attempt: number }; StoreFull: {} },
{
readonly describe: () => string;
/** The next state after a failed attempt: retry until `MAX_ATTEMPTS`, then give up. */
readonly nextAttempt: () => UploadError;
}
>;
export const UploadError = constructors<UploadError>().impl({
MAX_ATTEMPTS: 3,
describe: (error): string =>
match(error, {
Invalid: ({ problem }) => `invalid: ${CheckError.describe(problem)}`,
Retrying: ({ attempt }) => `retrying (attempt ${attempt})`,
StoreFull: () => "the store is full",
}),
nextAttempt: (error): UploadError =>
match(error, {
Retrying: ({ attempt }) =>
attempt >= UploadError.MAX_ATTEMPTS ? ({ tag: "StoreFull" } satisfies __EnumData<UploadError> as UploadError) : ({ tag: "Retrying", attempt: attempt + 1 } satisfies __EnumData<UploadError> as UploadError),
_: () => ({ tag: "Retrying", attempt: 1 } satisfies __EnumData<UploadError> as UploadError),
}),
});
export function messages(errors: readonly UploadError[]): string[] {
{ const __la1 = errors; const __lr1: any[] = new Array(__la1.length); for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let error = __le1; __lr1[__li1] = (UploadError.describe(UploadError.nextAttempt(error))); }} return __lr1; }
}- The value comes first, typed for you:
describe: (error) => ...needs no annotations. A method that builds variants through the table it is part of (nextAttemptabove) writes its return type; without it TypeScript can't infer the type of a table that refers to itself while it is being declared. - Every declared method is implemented, with the declared types; a missing one doesn't compile. A hand-written
{ tag: "StoreFull" }is noUploadErrorany more (it has no methods): values come from the constructors. implalso takes functions and constants of the table's own (UploadError.MAX_ATTEMPTS, a constant that keeps its literal type3). No objects, arrays orMaps: the table is shared by the whole program, so state put there would be one global. State that belongs to one value goes in its variant (Retrying: { attempt }), and a method returns the next variant instead of changing a counter. The table is read-only: a write to it throws.
What the build does with it. The values stay plain objects with no methods of their own. The build turns each call into a call of the table: error.nextAttempt().describe() becomes UploadError.describe(UploadError.nextAttempt(error)), so a method costs what a function call costs, and JSON.stringify, validate<T>, spreads and structuredClone keep every value whole. (A prototype on the values would cost more: measured in packages/std/bench/enum-methods.bench.ts, method calls up to 3× slower once an enum has more than about four variants, JSON.stringify 1.5× slower on Node, and values from JSON.parse, a spread or structuredClone would lose their methods while the type still claimed them.) The table form is the same function, for passing it on: errors.map(UploadError.describe).
To turn a call into the table's, the build follows the value through what the source declares: a parameter or local declared UploadError (or Option<UploadError>, a Variant of it), an item of a declared list or map, a field, a function's declared return type, a constructor's result, a match handler's value, variant(...)'s result, and the value a method gets. Anything it can't follow is an error, never left to fail at run time:
enum-method-receiver: a call whose value's type isn't declared anywhere the checker follows, in a form the rewrite doesn't take (error.describe?.()), in a Vue template, or a method taken off its value (const f = error.describe). Declare the type (const picked: UploadError = ...), or call the table.enum-method-escape: a value given where a type naming one of its methods is declared ({ readonly describe: () => string }): code there would call the method on a value that has none.enum-method-name: a method named like a built-in's or a library's (get,next,map,update, andObject.prototype'stoString,valueOf): a call of it the checker can't follow couldn't be told apart from the enum's. Give it a name that says what it does for this enum.
Text. An enum value turned into text is "[object Object]": ${error}, String(error), error + "..." and errors.join(", ") are errors (enum-as-text), for every enum. Call the method that gives its text: ${error.describe()}. toString can't be a method: the language calls it out of sight of the build. A value whose type the checker can't follow isn't checked here (it prints "[object Object]" too, but never fails).
Part of an enum
Variant<E, "A" | "B"> is the part of E with those variants. It can have its own constructors, and its values are values of the whole enum:
✓ Accepted0 diagnostics
ts
import { constructors, type Enum, match, type Variant } from "@evobug_com/safe-ts-std/enum";
export type Command = Enum<{ Move: { from: number; to: number }; Clear: {}; Attach: { file: string } }>;
export const Command = constructors<Command>();
/** The commands that run locally, without an upload. */
export type LocalCommand = Variant<Command, "Move" | "Clear">;
export const LocalCommand = constructors<LocalCommand>();
export const clear: Command = LocalCommand.Clear();
function applyLocally(command: LocalCommand): string {
return match(command, { Move: ({ from, to }) => `move ${from} to ${to}`, Clear: () => "clear" });
}
export function apply(command: Command): string {
// `_` gets the variants without their own handler: here, a `LocalCommand`.
return match(command, { Attach: ({ file }) => `attach ${file}`, _: (local) => applyLocally(local) });
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { constructors, type Enum, match, type Variant } from "@evobug_com/safe-ts-std/enum";
export type Command = Enum<{ Move: { from: number; to: number }; Clear: {}; Attach: { file: string } }>;
export const Command = constructors<Command>();
/** The commands that run locally, without an upload. */
export type LocalCommand = Variant<Command, "Move" | "Clear">;
export const LocalCommand = constructors<LocalCommand>();
export const clear: Command = ({ tag: "Clear" } satisfies LocalCommand as LocalCommand);
function applyLocally(command: LocalCommand): string {
{ const __ms1 = command; let __mv1: string; switch (__ms1.tag) { case "Move": { const { from, to } = __ms1; __mv1 = `move ${from} to ${to}`; break; } case "Clear": { __mv1 = "clear"; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}
export function apply(command: Command): string {
// `_` gets the variants without their own handler: here, a `LocalCommand`.
{ const __ms2 = command; let __mv2: string; switch (__ms2?.tag) { case "Attach": { const { file } = __ms2; __mv2 = `attach ${file}`; break; } default: { const local = __ms2; __mv2 = applyLocally(local); break; } } return __mv2; }
}When you only care about one variant
_ in match handles every variant that has no handler of its own, and gets just those variants (here Draft or Archived):
✓ Accepted0 diagnostics
ts
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
type Status = Enum<{ Draft: {}; Published: { at: string }; Archived: { reason: string } }>;
export function publishedOn(status: Status): string {
return match(status, {
Published: ({ at }) => `published on ${at}`,
_: () => "not published yet",
});
}ts
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
type Status = Enum<{ Draft: {}; Published: { at: string }; Archived: { reason: string } }>;
export function publishedOn(status: Status): string {
{ const __ms1 = status; let __mv1: string; switch (__ms1?.tag) {
case "Published": { const { at } = __ms1; __mv1 = `published on ${at}`; break; }
default: { __mv1 = "not published yet"; break; } } return __mv1; }
}is(value, ...variants) asks "is it this variant?", and TypeScript narrows the type, inside filter too. Name the variant by its constructor, or by its tag when there are no constructors:
✓ Accepted0 diagnostics
ts
import { constructors, type Enum, is } from "@evobug_com/safe-ts-std/enum";
type Status = Enum<{ Draft: {}; Published: { at: string }; Archived: { reason: string } }>;
const Status = constructors<Status>();
export function isLive(status: Status): boolean {
return is(status, Status.Published);
}
export function isHidden(status: Status): boolean {
return is(status, Status.Draft, Status.Archived);
}
export function publishDates(statuses: readonly Status[]): readonly string[] {
return statuses.filter((s) => is(s, Status.Published)).map((s) => s.at);
}ts
import { constructors, type Enum, is } from "@evobug_com/safe-ts-std/enum";
type Status = Enum<{ Draft: {}; Published: { at: string }; Archived: { reason: string } }>;
const Status = constructors<Status>();
export function isLive(status: Status): boolean {
return (status?.tag === "Published");
}
export function isHidden(status: Status): boolean {
return (status?.tag === "Draft" || status?.tag === "Archived");
}
export function publishDates(statuses: readonly Status[]): readonly string[] {
{ const __la1 = statuses; const __ls1_0 = __la1.filter((s) => (s?.tag === "Published")); const __lr1: any[] = new Array(__ls1_0.length); for (let __li1 = 0, __ln1 = __ls1_0.length; __li1 < __ln1; __li1++) { if (!(__li1 in __ls1_0)) continue; const __le1 = __ls1_0[__li1]!; { let s = __le1; __lr1[__li1] = (s.at); }} return __lr1; }
}is(status, Status.Published({ at })) doesn't compile: that is a value, not a variant.
The build turns is with constant variants into the tag check, status?.tag === "Published", so it costs no call. With several variants, the value must be a plain variable, so that it is still evaluated once; otherwise the call stays. is(status, "Published") compiles to the same check: when the enum has constructors, use them anyway, so that a rename and go-to-definition follow the variant. With the idiomatic rules on, prefer-constructor-tag asks for that.
Tags are strings, and comparing them is as fast as comparing numbers when the engine has interned them: tags written in the code, parsed by JSON.parse or checked by validate<T>. Performance myths has the measurements, the case that is slower (a tag built at runtime, such as a word cut from a string), and why tags don't become numbers.
variant(value, Status.Archived) gives you the value if it's that variant, and undefined otherwise, so it works with ?. and ??. On a plain variable, the build turns it into status?.tag === "Archived" ? status : undefined:
✓ Accepted0 diagnostics
ts
import { constructors, type Enum, variant } from "@evobug_com/safe-ts-std/enum";
type Status = Enum<{ Draft: {}; Published: { at: string }; Archived: { reason: string } }>;
const Status = constructors<Status>();
export function archiveReason(status: Status): string {
return variant(status, Status.Archived)?.reason ?? "not archived";
}ts
import { constructors, type Enum, variant } from "@evobug_com/safe-ts-std/enum";
type Status = Enum<{ Draft: {}; Published: { at: string }; Archived: { reason: string } }>;
const Status = constructors<Status>();
export function archiveReason(status: Status): string {
return (status?.tag === "Archived" ? status : undefined)?.reason ?? "not archived";
}Checking the tag by hand narrows the type too, and the default rules accept it. Use is, variant or match anyway: with the idiomatic rules on, prefer-is-over-tag asks for them instead of .tag === "..." and switch (x.tag).
✅ Also accepted: a tag check, in a project without the idiomatic rules
✓ Accepted0 diagnostics
ts
import type { Enum } from "@evobug_com/safe-ts-std/enum";
type Status = Enum<{ Draft: {}; Published: { at: string }; Archived: { reason: string } }>;
export function describe(status: Status): string {
if (status.tag === "Published") return `live since ${status.at}`;
return "not live";
}Which one? Use a full match when every variant needs its own decision: adding a variant then makes you look at this code again. Use _, is or variant when the other variants really are "everything else". They won't remind you when a variant is added.
That holds for one test. A chain that tests two variants or more (if (is(s, "A")) ... else if (is(s, "B")) ... else ...) is a decision per variant written by hand, and its last else takes every variant added later: exhaustive-dispatch reports it unless it handles them all. Write it as a match, with _ where the rest really share a branch.
(If you know Rust: _ is _ =>, is is matches!, and variant is if let.)
Matching an Option
A value that may be missing is an Option of the enum: Option<Delivery>, which is Delivery | undefined. match takes it directly. The undefined handler says what a missing value gives:
✓ Accepted0 diagnostics
ts
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
import type { Option } from "@evobug_com/safe-ts-std/result";
type Address = { readonly street: string; readonly city: string };
type Delivery = Enum<{ pickup: { at: Address }; ship: { to: Address }; download: {} }>;
type Order = { readonly delivery: Option<Delivery>; readonly billing: Address };
export function deliveryAddress(order: Order): Option<Address> {
return match(order.delivery, {
pickup: (delivery) => delivery.at,
ship: (delivery) => delivery.to,
download: () => order.billing,
undefined: () => undefined,
});
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
import type { Option } from "@evobug_com/safe-ts-std/result";
type Address = { readonly street: string; readonly city: string };
type Delivery = Enum<{ pickup: { at: Address }; ship: { to: Address }; download: {} }>;
type Order = { readonly delivery: Option<Delivery>; readonly billing: Address };
export function deliveryAddress(order: Order): Option<Address> {
{ const __ms1 = order.delivery; let __mv1: Option<Address>; switch (__ms1?.tag) {
case "pickup": { const delivery = __ms1; __mv1 = delivery.at; break; }
case "ship": { const delivery = __ms1; __mv1 = delivery.to; break; }
case "download": { __mv1 = order.billing; break; }
case undefined satisfies typeof __ms1: { __mv1 = undefined; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}The handler is named undefined because that is what a missing value is: there is no None wrapper. That also leaves the name None free for a variant of your own.
_ covers a missing value too, along with the variants left, so its parameter may be undefined:
✓ Accepted0 diagnostics
ts
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
import type { Option } from "@evobug_com/safe-ts-std/result";
type Address = { readonly street: string; readonly city: string };
type Delivery = Enum<{ pickup: { at: Address }; ship: { to: Address }; download: {} }>;
type Order = { readonly delivery: Option<Delivery> };
export function pickupPoint(order: Order): Option<Address> {
return match(order.delivery, { pickup: (delivery) => delivery.at, _: () => undefined });
}
export function deliveryNote(order: Order): string {
return match(order.delivery, { undefined: () => "choose a delivery", _: () => "delivery chosen" });
}ts
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
import type { Option } from "@evobug_com/safe-ts-std/result";
type Address = { readonly street: string; readonly city: string };
type Delivery = Enum<{ pickup: { at: Address }; ship: { to: Address }; download: {} }>;
type Order = { readonly delivery: Option<Delivery> };
export function pickupPoint(order: Order): Option<Address> {
{ const __ms1 = order.delivery; let __mv1: Option<Address>; switch (__ms1?.tag) { case "pickup": { const delivery = __ms1; __mv1 = delivery.at; break; } default: { __mv1 = undefined; break; } } return __mv1; }
}
export function deliveryNote(order: Order): string {
{ const __ms2 = order.delivery; let __mv2: string; switch (__ms2?.tag) { case undefined satisfies typeof __ms2: { __mv2 = "choose a delivery"; break; } default: { __mv2 = "delivery chosen"; break; } } return __mv2; }
}It is still exhaustive. If the value may be missing, the match needs an undefined handler or _, or it doesn't compile. On a value that can't be missing, an undefined handler doesn't compile either, like a misspelled variant.
is and variant take an Option too. A missing value is none of the variants: is gives false, variant gives undefined.
✓ Accepted0 diagnostics
ts
import { type Enum, is, variant } from "@evobug_com/safe-ts-std/enum";
import type { Option } from "@evobug_com/safe-ts-std/result";
type Address = { readonly street: string; readonly city: string };
type Delivery = Enum<{ pickup: { at: Address }; ship: { to: Address }; download: {} }>;
export function isShipped(delivery: Option<Delivery>): boolean {
return is(delivery, "ship");
}
export function shipTo(delivery: Option<Delivery>): Option<Address> {
return variant(delivery, "ship")?.to;
}ts
import { type Enum, is, variant } from "@evobug_com/safe-ts-std/enum";
import type { Option } from "@evobug_com/safe-ts-std/result";
type Address = { readonly street: string; readonly city: string };
type Delivery = Enum<{ pickup: { at: Address }; ship: { to: Address }; download: {} }>;
export function isShipped(delivery: Option<Delivery>): boolean {
return (delivery?.tag === "ship");
}
export function shipTo(delivery: Option<Delivery>): Option<Address> {
return (delivery?.tag === "ship" ? delivery : undefined)?.to;
}The build turns these into a switch on value?.tag with case undefined:, and into value?.tag === "ship", as for any other value.
(In Rust: match opt { Some(Delivery::Pickup(..)) => .., None => .. }, with _ covering None as well; is is matches!(opt, Some(..)).)
Matching a union of strings
Plain names without data are a union of strings ("open" | "urls" | "help"), and match takes one the same way as an enum: a handler per member, named by the string, _ for the members left, and an undefined handler for an Option of one. Forget a member and it doesn't compile.
✓ Accepted0 diagnostics
ts
import { match } from "@evobug_com/safe-ts-std/enum";
import type { Option } from "@evobug_com/safe-ts-std/result";
type Command = "open" | "urls" | "help";
export function describe(command: Command): string {
return match(command, {
open: () => "opens every app",
urls: () => "lists the URLs",
help: () => "this text",
});
}
export function shortcut(command: Option<Command>): Option<string> {
return match(command, { open: () => "o", undefined: () => undefined, _: (other) => other });
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { match } from "@evobug_com/safe-ts-std/enum";
import type { Option } from "@evobug_com/safe-ts-std/result";
type Command = "open" | "urls" | "help";
export function describe(command: Command): string {
{ const __ms1 = command; let __mv1: string; switch (__ms1) {
case "open": { __mv1 = "opens every app"; break; }
case "urls": { __mv1 = "lists the URLs"; break; }
case "help": { __mv1 = "this text"; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}
export function shortcut(command: Option<Command>): Option<string> {
{ const __ms2 = command; let __mv2: Option<string>; switch (__ms2) { case "open": { __mv2 = "o"; break; } case undefined satisfies typeof __ms2: { __mv2 = undefined; break; } default: { const other = __ms2!; __mv2 = other; break; } } return __mv2; }
}Each handler gets its member, and _ the members without a handler of their own (here "urls" | "help"). The build turns the call into a switch on the value. A value typed string doesn't compile: it is no closed set, so parse it into the union first (see string-dispatch).
Numbers aren't matched, because handler names are strings: for a union of numbers or a code object of numbers, use a switch that ends in unreachable, or a table typed by the set (below).
In a Vue template or JSX, <Match> takes an enum only, not yet a union of strings: use v-if chains there, or match in a computed.
Prefer switch? End it with unreachable
match is the default way to handle every variant: it doesn't compile when one is missing. A switch works too, if it ends with default: unreachable(value): then TypeScript checks that every variant has a case. On a union of numbers, which match doesn't take, it is the form to use. exhaustive-switch asks for it on any closed set: an enum's tag, a union of literals, a code object (below).
❌ Rejected: a new variant would silently fall through
✕ Rejectedexhaustive-switch
ts
import type { Enum } from "@evobug_com/safe-ts-std/enum";
type Status = Enum<{ Active: {}; Suspended: { reason: string } }>;
export function label(status: Status): string {
switch (status.tag) {
case "Active":
return "active";
case "Suspended":
return `suspended: ${status.reason}`;
}
return "unknown";
}✓ Accepted0 diagnostics
ts
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
type Status = Enum<{ Active: {}; Suspended: { reason: string } }>;
export function label(status: Status): string {
return match(status, {
Active: () => "active",
Suspended: ({ reason }) => `suspended: ${reason}`,
});
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
type Status = Enum<{ Active: {}; Suspended: { reason: string } }>;
export function label(status: Status): string {
{ const __ms1 = status; let __mv1: string; switch (__ms1.tag) {
case "Active": { __mv1 = "active"; break; }
case "Suspended": { const { reason } = __ms1; __mv1 = `suspended: ${reason}`; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}✅ Also accepted: a switch that ends in unreachable, in a project without the idiomatic rules
✓ Accepted0 diagnostics
ts
import { type Enum, unreachable } from "@evobug_com/safe-ts-std/enum";
type Status = Enum<{ Active: {}; Suspended: { reason: string } }>;
export function label(status: Status): string {
switch (status.tag) {
case "Active":
return "active";
case "Suspended":
return `suspended: ${status.reason}`;
default:
return unreachable(status);
}
}Listing the variants
variants<T>() (from @evobug_com/safe-ts-std/enum, also in the prelude) is the tags of an enum, in declaration order, as a frozen array typed readonly T["tag"][]. The build writes the list from the type, as it writes validators, so a tool or a form that goes through every variant stays in step with the type. (constructors<T>() makes each constructor when it's used, so Object.keys of it is empty.) It reads only the tags: the variants' fields aren't evaluated, so a field whose type a validator can't check (a Date, a type computed from an array) doesn't stop it.
✓ Accepted0 diagnostics
ts
import { type Enum, variants } from "@evobug_com/safe-ts-std/enum";
export type Payment = Enum<{ Card: { last4: string }; Transfer: { iban: string }; Cash: {} }>;
export const PAYMENT_METHODS = variants<Payment>(); // ["Card", "Transfer", "Cash"]
export function methodOptions(): string[] {
return PAYMENT_METHODS.map((tag) => `<option>${tag}</option>`);
}ts
import { type Enum, variants } from "@evobug_com/safe-ts-std/enum";
export type Payment = Enum<{ Card: { last4: string }; Transfer: { iban: string }; Cash: {} }>;
export const PAYMENT_METHODS = (Object.freeze(["Card", "Transfer", "Cash"] as const) satisfies readonly (Payment)["tag"][] as readonly (Payment)["tag"][]); // ["Card", "Transfer", "Cash"]
export function methodOptions(): string[] {
{ const __la1 = PAYMENT_METHODS; const __lr1: any[] = new Array(__la1.length); for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let tag = __le1; __lr1[__li1] = (`<option>${tag}</option>`); }} return __lr1; }
}Code tables
A value that goes into a save file or onto the wire is often a number from a table: { NONE: 0, MOVE: 1, GATHER: 2 } as const, with (typeof Job)[keyof typeof Job] as its type. Each code must stay unique. Numbered by hand, they collide when two branches each add one: both pick the next free number, and the merge keeps both lines. duplicate-code-value reports two names with one value, in a table, in a literal union and in the labels of a switch.
Better, don't number them by hand. Derive the codes from an append-only list of names (codesOf, in the JSON guide): a new code is an appended name, and a merge that keeps both sides gives each name its own index. Mark a table whose values don't follow a pattern the checker knows /** @unique */, and it is checked too:
✕ Rejectedduplicate-code-value
ts
/** @unique */
export const Port = { Http: 80, Admin: 8080, Proxy: 80 } as const;Lists that keep an order
Some lists must keep an order or stay free of repeats: the features of an encoding (each one adds a field, in order), names hashed into a version, a list searched by bisection. A comment saying so doesn't stop an append at the end. Say it with a tag the checker verifies instead: /** @sorted */ (ascending; strings as sort() orders them) and /** @unique */, on a module-level [...] as const or Object.freeze([...]) of strings or numbers. list-invariant reports the first element out of order, with the place it belongs, and the second of two equal ones.
✕ Rejectedlist-invariant
ts
/** @sorted @unique */
export const FEATURES = Object.freeze(["library", "pub", "marchTogether"]);✓ Accepted0 diagnostics
ts
/** @sorted @unique */
export const FEATURES = Object.freeze(["library", "marchTogether", "pub"]);Don't use TypeScript's enum
TypeScript's own enum has surprises: a numeric enum accepts any number (const c: Color = n compiles for any n: number, even one that is no member), and Node can't run a file that contains one without a compiler.
✕ Rejectedno-ts-enum
ts
export enum Color {
Red,
Green,
}For plain named constants, a union of strings is all you need, and match handles it (Matching a union of strings):
✓ Accepted0 diagnostics
ts
import { match } from "@evobug_com/safe-ts-std/enum";
export type Color = "red" | "green";
export function hex(color: Color): string {
return match(color, { red: () => "#f00", green: () => "#0f0" });
}ts
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { match } from "@evobug_com/safe-ts-std/enum";
export type Color = "red" | "green";
export function hex(color: Color): string {
{ const __ms1 = color; let __mv1: string; switch (__ms1) { case "red": { __mv1 = "#f00"; break; } case "green": { __mv1 = "#0f0"; break; } default: __mv1 = __matchUnreachable(__ms1); } return __mv1; }
}If your code uses Color.Red, the quick fix turns the enum into a constant object and a type, with the same values:
✓ Accepted0 diagnostics
ts
export const Color = { Red: 0, Green: 1 } as const;
export type Color = (typeof Color)[keyof typeof Color];
export const favourite: Color = Color.Green;A dispatch on a union or a code object
A union of literals and an object of constants (as const, or a codesOf(...) table, see JSON) are closed sets too, and the same bug hides in a chain on them: the branches name the members one by one, and the last else takes the rest, including a member added later. A phase added to Phase gets its branch where it was added, and 0 everywhere else:
✕ Rejectedexhaustive-dispatch
ts
export const Phase = Object.freeze({ WALK: 0, RUN: 1, TEND: 2 });
export type Phase = (typeof Phase)[keyof typeof Phase];
export function speed(phase: Phase): number {
if (phase === Phase.WALK) return 1;
if (phase === Phase.RUN) return 2;
return 0;
}exhaustive-dispatch reports a chain that tests two members or more and leaves some out. For a union of strings, match it. For numbers, handle every member, in a switch that ends with unreachable or in a table typed by the set; TypeScript then checks both:
✓ Accepted0 diagnostics
ts
export const Phase = Object.freeze({ WALK: 0, RUN: 1, TEND: 2 });
export type Phase = (typeof Phase)[keyof typeof Phase];
const SPEED: Readonly<Record<Phase, number>> = { [Phase.WALK]: 1, [Phase.RUN]: 2, [Phase.TEND]: 0 };
export function speed(phase: Phase): number {
return SPEED[phase];
}Type the value as the set (phase: Phase, not number). The rule also finds the set when the value is a number and every constant compared with comes from one object, but only the type lets TypeScript check a switch or a table.
A plain string compared with many words (if (word === "open") ... if (word === "urls") ...) is a set that exists only as those tests. Parse it once, where it comes in, into a union (a table maps the words, aliases included, to the members), and match on that: string-dispatch, an idiomatic rule, reports the chain.
Name the members, not the rest
A chain isn't the only test that leaves a new member to chance. Three more do, and each has the same fix: say which members you mean, in one place.
Tests that name the members they leave out
u.phase === Phase.INSIDE && u.job !== Job.FLEE is work for "every job but FLEE", a list that grows by itself: a WORSHIP job added later takes the branch. negative-member-guard reports an exclusion that guards work in a branch narrowed by another member test, or one that excludes two members or more. Name the members the work is for:
✓ Accepted0 diagnostics
ts
export const Job = Object.freeze({ STUDY: 0, TEACH: 1, FLEE: 2, WORSHIP: 3 });
export type Job = (typeof Job)[keyof typeof Job];
/** Jobs with work inside a building. */
export const KEEPS_WORK: ReadonlySet<Job> = new Set([Job.STUDY, Job.TEACH]);
export function keepsWork(job: Job): boolean {
return KEEPS_WORK.has(job);
}Ranges of codes
The codes of a codesOf(...) table are places in a list, and a new name goes at the end. So afterJob >= Job.MOVE && afterJob <= Job.IGNITE takes in the names between the two today, and never the ones added later. code-range-compare reports an order compare with such a constant. Name the members instead, or, where the order is what the names mean (life stages, levels), mark the table:
✓ Accepted0 diagnostics
ts
/** Life stages, in the order a unit lives them. @ordered */
export const Stage = Object.freeze({ BABY: 0, CHILD: 1, ADULT: 2, ELDER: 3 });
export type Stage = (typeof Stage)[keyof typeof Stage];
export function grown(stage: Stage): boolean {
return stage >= Stage.ADULT;
}One set, not copies
x === A || x === B written in a check, and again (with a member more, or less) in a reader or a writer, is two sets that drift. inline-member-set (by safe-ts check, which sees the whole program) reports the same value tested against sets that share members in more than one function, and names what differs. Export one ReadonlySet (or one match) and use it everywhere.
Rules in this guide: no-ts-enum, exhaustive-switch, exhaustive-dispatch, negative-member-guard, code-range-compare, inline-member-set, enum-constructors, string-dispatch, duplicate-code-value, list-invariant