typescript / expert
Snippet
Phantom Type State Machines for Privileged Security Workflows
Uses phantom type parameters and explicit 'this' parameter typing to construct compile-time state machines. Methods like 'execute' are completely inaccessible prior to passing authorization checks in 'verify'.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface Unverified {}interface Verified {}class SecurityPipeline<State = Unverified> {private constructor(private readonly payload: string) {}static create(payload: string): SecurityPipeline<Unverified> {return new SecurityPipeline<Unverified>(payload);}verify(this: SecurityPipeline<Unverified>, secret: string): SecurityPipeline<Verified> {if (secret !== "SECRET_KEY") throw new Error("Invalid key");return new SecurityPipeline<Verified>(this.payload);}execute(this: SecurityPipeline<Verified>): string {return `Executing payload: ${this.payload}`;}}
Breakdown
1
class SecurityPipeline<State = Unverified>
Defines phantom state generic marker parameter that carries no runtime overhead.
2
verify(this: SecurityPipeline<Unverified>, ...)
Restricts invocation strictly to instances currently residing in the Unverified state.
3
execute(this: SecurityPipeline<Verified>): string
Compile-time guard enforcing that execution can only be invoked on Verified pipelines.