typescript / expert
Snippet
Phantom Type Parameters with Branded Types for Compile-Time State Verification
Combines phantom type parameters with unique symbol nominal branding to create compile-time state machines without runtime overhead.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
declare const StateBrand: unique symbol;type State<S extends string> = { readonly [StateBrand]: S };type Draft = State<"DRAFT">;type Published = State<"PUBLISHED">;type Document<S extends State<string>> = {id: string;content: string;_state: S;};function createDocument(content: string): Document<Draft> {return { id: "doc-1", content, _state: null as any };}function publishDocument(doc: Document<Draft>): Document<Published> {return { ...doc, _state: null as any };}
Breakdown
1
declare const StateBrand: unique symbol;
Creates an unforgeable unique symbol key for nominal brand typing.
2
type State<S extends string> = { readonly [StateBrand]: S };
Defines nominal brand container parameterized by literal state string S.
3
function publishDocument(doc: Document<Draft>): Document<Published>
Enforces that only documents strictly in the Draft phantom state can be published.