typescript / expert
Snippet
Kompilierzeit-Zustandsautomaten-Guards mit Phantom-Typen
Phantom-Typparameter heften Typ-Level-Tags an Laufzeit-Instanzen an, ohne deren zugrunde liegende Datenstruktur zu verändern. Dies verhindert ungültige Lebenszyklus-Zustandsübergänge zur Kompilierzeit in der Kernanwendungslogik.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
type Draft = { state: 'DRAFT' };type Published = { state: 'PUBLISHED' };class DocumentProcess<State> {constructor(public readonly content: string) {}static create(content: string): DocumentProcess<Draft> {return new DocumentProcess<Draft>(content);}}function publishDocument(doc: DocumentProcess<Draft>): DocumentProcess<Published> {return new DocumentProcess<Published>(doc.content);}const draftDoc = DocumentProcess.create('Framework Core RFC');const publishedDoc = publishDocument(draftDoc);// publishDocument(publishedDoc); // Compile Error: Argument of type 'DocumentProcess<Published>' is not assignable to 'DocumentProcess<Draft>'
Erklärung
1
class DocumentProcess<State> {
Deklariert eine Klasse mit einem Phantom-Generics-Parameter 'State', der rein zur Kompilierzeit für die Typverfolgung existiert.
2
static create(content: string): DocumentProcess<Draft>
Factory-Methode, die den Dokumenten-Workflow instanziiert und strikt an das initiale 'Draft'-State-Tag bindet.
3
function publishDocument(doc: DocumentProcess<Draft>): DocumentProcess<Published>
Übergangsfunktion, die nur Dokumente im Zustand 'Draft' akzeptiert und eine neue Instanz als 'Published' getaggt zurückgibt.
4
// publishDocument(publishedDoc); // Compile Error
Demonstriert die Typprüfung, die ungültige erneute Veröffentlichungsoperationen vor der Ausführung verhindert.