typescript / expert
Snippet
Phantom-Typparameter mit Brand-Typen zur Zustandsvalidierung zur Kompilierzeit
Kombiniert Phantom-Typparameter mit eindeutigen Symbol-Brandings, um Zustandsübergänge ohne Laufzeit-Overhead zur Kompilierzeit zu erzwingen.
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 };}
Erklärung
1
declare const StateBrand: unique symbol;
Erstellt einen unfaälschbaren eindeutigen Symbol-Schlüssel für nominales Branding.
2
type State<S extends string> = { readonly [StateBrand]: S };
Definiert ein nominales Branding-Konstrukt, das über den Literal-String S parametrisiert wird.
3
function publishDocument(doc: Document<Draft>): Document<Published>
Stellt sicher, dass nur Dokumente im exakten Entwurfszustand (Draft) veröffentlicht werden können.