javascript / expert
Snippet
Typsichere State-Machines mit useReducer und Discriminated Unions
Die Verwendung von TypeScript Discriminated Unions mit Reacts useReducer erstellt eine formale State-Machine. Dieses Muster stellt sicher, dass nur valide Zustandsübergänge möglich sind und eliminiert 'unmögliche Zustände' (wie das gleichzeitige Vorhandensein von Daten und Fehlern).
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
type State =| { status: 'idle' }| { status: 'loading' }| { status: 'success'; data: string[] }| { status: 'error'; error: Error };type Action =| { type: 'FETCH' }| { type: 'RESOLVE'; payload: string[] }| { type: 'REJECT'; error: Error };const reducer = (state: State, action: Action): State => {switch (state.status) {case 'idle':return action.type === 'FETCH' ? { status: 'loading' } : state;case 'loading':return action.type === 'RESOLVE'? { status: 'success', data: action.payload }: action.type === 'REJECT'? { status: 'error', error: action.error }: state;default:return state;}};
react
Erklärung
1
type State = ...
Definiert sich gegenseitig ausschließende Zustände, um illegale Eigenschaftskombinationen zu verhindern.
2
switch (state.status)
Nutzt die exhaustive Überprüfung von TypeScript, um sicherzustellen, dass alle Zustände bei Übergängen korrekt behandelt werden.