Files
2026-07-20 09:58:50 +02:00

2.5 KiB

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., bool flags) 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 PhantomData to track state.

Go

TypeScript

  • 07-typestate-ts: Implementing the Typestate pattern in TypeScript using this type 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