ondras / rot.js

ROguelike Toolkit in JavaScript. Cool dungeon-related stuff, interactive manual, documentation, tests!
https://ondras.github.io/rot.js/hp/
BSD 3-Clause "New" or "Revised" License
2.33k stars 254 forks source link

Strictly type parameter of getWeightedValue #147

Closed bbugh closed 5 years ago

bbugh commented 5 years ago

Currently, getWeightedValue is typed as data: any, but it expects the set to have numeric values. This can result in compile-time validity but runtime errors.

Before PR

RNG.getWeightedValue({ 'monster': 'error!' }) // causes runtime error but compiles fine

After PR

// compile-time error: Type 'string' is not assignable to type 'number'.
RNG.getWeightedValue({ 'monster': 'error!' }) 

// works
RNG.getWeightedValue({ 'monster': 30, 50: 10 }) 

If the index signature looks a little odd, here's why: TypeScript expects index signatures to must be literal string or number, but doesn't allow you to have a string | number union. The type in this PR is a signature overload, so TS knows that if the key is a string or a number, the value must be a number, which covers all of the valid cases in TS/JS.

ondras commented 5 years ago

Thanks!