r/typescript • u/Savings_Extent • Jul 26 '25
Implementing an Entity Component System (ECS) in TypeScript: Design Tips and Performance Considerations?
Hey r/typescript,
I've been diving into data-oriented design patterns lately, and I wanted to get some thoughts from the community on building a simple Entity Component System (ECS) in TypeScript. For those unfamiliar, ECS is a great way to structure game-like or simulation code for better modularity and performance, even in a high-level language like TS—think separating entities (just IDs), components (pure data interfaces), and systems (logic handlers) to reduce inheritance mess and improve cache-friendly loops.
Here's a quick sketch of how I'm approaching it, inspired by some recent experiments:
- World Class: Acts as the central manager. Something like:
class World {
private nextEntityId: number = 0;
private components: Map<number, Map<string, any>> = new Map();
// ... methods for createEntity, addComponent, etc.
query(required: string[]): number[] {
// Filter entities with all required components
}
update(dt: number) {
// Run systems
}
}- Entities: Just
type Entity = number;– super lightweight. - Components: Interfaces for data only, e.g.:
interface Position { x: number; y: number; }
interface Velocity { dx: number; dy: number; }- Systems: An interface like
interface System {
update(world: World, dt: number): void;
}with implementations batch-processing queries, e.g., a MovementSystem looping over Position + Velocity entities for efficient updates.
The goal is to leverage TS's type safety while keeping things performant in JS environments (e.g., browsers or Node)—array-based storage for components helps with iteration speed and GC minimization.
What do you all think? Any gotchas with this setup for larger projects? Tips on optimizing queries (bitmasks? archetypes?) or handling TypeScript-specific quirks like generics for components? Has anyone used ECS in TS for games/simulations and seen real perf gains over OOP?
I'm tinkering with a basic implementation right now and streaming the process on Twitch CodingButter if you're curious about the live tweaks—feel free to share code snippets or ideas here!
Looking forward to your insights! 🚀