Skip to content

A strange experiment to play chess inside TypeScript's type system

License

Notifications You must be signed in to change notification settings

scottbedard/chess-types

Repository files navigation

@bedard/chess-types

Test NPM License

Welcome to a strange experiment to play chess inside TypeScript's type system.

Check out the sandbox →

Basic usage

Create a game and apply moves using {from}{to}{promotion?} strings. Castling is done via O-O and O-O-O syntax, lowercase for black.

import type {
  Chessboard,
  FormatGame,
  NewGame,
  NextMove,
} from '@bedard/chess-types'

type Game = NewGame<[
  'e2e4', 'e7e5',
  'g1f3', 'b8c6',
  'f1c4', 'f8c5',
  'O-O',  // ...
]>

type CpuMove = NextMove<Game> // <- play against the compiler!

type Board = Chessboard<Game> // <- hover to see the current board state

// {
//     8: " r * b q k * n r ";
//     7: " p p p p * p p p ";
//     6: " - * n * - * - * ";
//     5: " * - b - p - * - ";
//     4: " - * B * P * - * ";
//     3: " * - * - * N * - ";
//     2: " P P P P - P P P ";
//     1: " R N B Q * R K - ";
// }

// finally, export the game as a string using FEN notation

type Fen = FormatGame<Game> // 'r1bqk1nr/pppp1ppp/2n5/2b1p3/2B1P3/5N2/PPPP1PPP/RNBQ1RK1 b kq - 5 4'

There are loads of other interesting types under the hood, like IsLegal, ParseFen, and Evaluate. So if you're into that kind of thing, by all means dig around and let me know what you think!

Side note, NextMove uses an extremely naive strategy. It simply adds up all the pieces and chooses the move with the best score. There are many improvements that could be made, but that was never the plan here. My goal was to play chess inside the compiler, not to build stockfish.

Final thoughts

TypeScript is amazing.

It's type system can be thought of as it's own purely functional language, but for obvious reasons it shouldn't be used as one. There was no practical reason for any of this beyond learning, but in that sense I've enjoyed it and feel like I've succeeded. More specifically, I've gained a new appreciation for the recursive accumulator pattern, and generic type inference.

If you find this repo interesting, here are some others you may like!

License

MIT

Copyright (c) 2025-present, Scott Bedard

About

A strange experiment to play chess inside TypeScript's type system

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published