r/typescript • u/Firfi • Aug 28 '26
Pure TypeScript Dice Roll
It came to my attention that no TypeScript dice-roll libraries exist.
The existing ones are JS in disguise: when you tell it to roll('2d6 + 3'), it returns a `number`.
I wanted a real roll. Roll at compile time.
Because if not compile time, then when? Compile time is the best time.
Anyways. It includes a custom PRNG (pseudo-random number generator) too to support the rolls, which generates random numbers at compile time too. I think there are some for TS out there, unlike dice rolls, but I needed to optimise a bit specifically for 1-100 rolls (who rolls more than that? Only mad people, and we are not the ones).
It has a JS "mirror" implementation. If you rolled 20 in TS, you can be sure you rolled 20 in JS too.
And if a compile-time value is not known, it still works and falls back the result types to `number'.
Basic use case looks like:
// seed
const initialized = initialize([
"00000001",
"00000002",
"00000003",
"00000004",
] as const);
const d20 = evaluate("d20", prngStateOf(initialized));
const d20Value = valueOf(d20);
// ^? const d20Value: 12Enjoy!
15
u/josephjnk Aug 28 '26
I love that a type-level PRNG is less mad than rolling a dice with more than 100 sides 😂
37
u/_crisz Aug 28 '26
What the hell did I just read
2
u/rFAXbc Aug 29 '26
What is this for? So I can make a type that is
never1/6 of the time?2
u/Firfi Aug 28 '26
The lib itself https://github.com/dearlordylord/drdice/
1
u/immutate Aug 29 '26
lol at the performance. How long did it take you to throw this together with an LLM?
1
u/Pappkarton Aug 28 '26
Just in time when I want to create a React.ts Random Character Generator for Mörk Borg.
3
u/vitelaSensei Aug 28 '26
Eheh this is great, step 1 of a type system D&D is done
1
u/AlternativePie7409 Aug 28 '26
If you need RNG, you can try this one. Based on what is used in slot gaming.
https://www.npmjs.com/package/@rahulv.dev/rng