typescript / expert
Snippet
State Transition Enforcement using Template Literal String Discriminators
This design leverages template literal types paired with generic constraint checking to construct compile-time finite state machines. Invalid state transitions trigger immediate type checking errors at the invocation site without requiring any runtime overhead or framework code.
snippet.ts
typescript
1
2
3
4
5
type State = 'IDLE' | 'LOADING' | 'SUCCESS';type Command = `GO_${State}`;type Rules = { IDLE: 'GO_LOADING'; LOADING: 'GO_SUCCESS'; SUCCESS: 'GO_IDLE' };type Validate<S extends State, C extends Command> = C extends Rules[S] ? C : never;function transition<S extends State, C extends Command>(current: S, cmd: Validate<S, C>): void {}
Breakdown
1
type Command = `GO_${State}`;
Generates dynamically typed string command union 'GO_IDLE' | 'GO_LOADING' | 'GO_SUCCESS'.
2
type Validate<S extends State, C extends Command> = C extends Rules[S] ? C : never;
Validates if requested command C is a valid state transition for current state S; evaluates to never if invalid.
3
function transition<S extends State, C extends Command>(current: S, cmd: Validate<S, C>): void {}
Enforces valid transition commands via type parameter validation directly in function argument signature.