dcef2470cb14df5c0b2a06b1b2ddcd4a7677a963
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: The initial problem where state is not managed, allowing operations in any order.
- 02-runtime-check: Adding runtime checks (e.g.,
boolflags) to ensure operations are performed in the correct state. - 03-builder-pattern: Using separate structs to represent different states, ensuring state transitions are enforced at compile-time.
- 04-typestate: A classic implementation of the Typestate pattern using generics and
PhantomDatato track state.
Go
- 05-typestate-go-structs: Implementing state transitions in Go using separate structs for each state.
- 06-typestate-go-interfaces: Using interfaces to restrict the available methods based on the current state of the object.
TypeScript
- 07-typestate-ts: Implementing the Typestate pattern in TypeScript using
thistype parameters to restrict method calls. - 08-type-mapping: Mapping enum values (like opcodes) to specific argument types for type-safe messaging.
- 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:
# Example: Running the typestate example
cargo run -p 04-typestate
Go
The Go examples can be run using the Go CLI:
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:
npx ts-node 07-typestate-ts/main.ts
Sources
Description
Demonstration of some type level programming patterns
59 KiB
0 Stars
1 Watchers
0 Forks
Languages
Rust
46.9%
TypeScript
28.8%
Go
24.3%