# Type Level Programming This repository contains a collection of examples demonstrating various type-level programming patterns in Rust, Go, and TypeScript. The goal of these examples is to show how to leverage the type system of a language to enforce invariants at compile-time, reducing the need for runtime checks and making the code more robust and self-documenting. ## Repository Structure The examples are organized by language and complexity. ### Rust The Rust examples demonstrate a progression of state management for a `CredentialManager`: - **[01-problem](./01-problem)**: The initial problem where state is not managed, allowing operations in any order. - **[02-runtime-check](./02-runtime-check)**: Adding runtime checks (e.g., `bool` flags) to ensure operations are performed in the correct state. - **[03-builder-pattern](./03-builder-pattern)**: Using separate structs to represent different states, ensuring state transitions are enforced at compile-time. - **[04-typestate](./04-typestate)**: A classic implementation of the Typestate pattern using generics and `PhantomData` to track state. ### Go - **[05-typestate-go-structs](./05-typestate-go-structs)**: Implementing state transitions in Go using separate structs for each state. - **[06-typestate-go-interfaces](./06-typestate-go-interfaces)**: Using interfaces to restrict the available methods based on the current state of the object. ### TypeScript - **[07-typestate-ts](./07-typestate-ts)**: Implementing the Typestate pattern in TypeScript using `this` type parameters to restrict method calls. - **[08-type-mapping](./08-type-mapping)**: Mapping enum values (like opcodes) to specific argument types for type-safe messaging. - **[09-type-programming](./09-type-programming)**: Advanced recursive type parsing to extract parameters from URL string literals at compile-time. ## Getting Started ### Rust You can run the Rust examples using Cargo from the root directory: ```bash # Example: Running the typestate example cargo run -p 04-typestate ``` ### Go The Go examples can be run using the Go CLI: ```bash go run ./05-typestate-go-structs ``` ### TypeScript The TypeScript examples are best viewed in an IDE (like VS Code) to see the type errors and completions. You can also run them using `ts-node`: ```bash npx ts-node 07-typestate-ts/main.ts ``` ## Sources - https://www.emoses.org/posts/resolver-resolved-pattern/ - https://farazdagi.com/posts/2024-04-07-typestate-pattern/ - https://youtu.be/_ccDqRTx-JU - https://type-level-typescript.com/