scurker / currency.js

A javascript library for handling currencies
https://currency.js.org
MIT License
3.15k stars 142 forks source link

Missing types in currency.Any #446

Open jonaspohren opened 1 year ago

jonaspohren commented 1 year ago

The currency.d.ts should be updated to also include undefined and null on currency.Any, because when passing those values it defaults to 0.

This code works fine, but TypeScript complains: currency(null).add(undefined).value; // 0

scurker commented 1 year ago

What's the value in having a less restrictive type? It's intended for currency.js to try and parse the value and it seems like passing in null or undefined should raise flags as that might be accidental.

jonaspohren commented 1 year ago

In my project I have a lot of possible undefined fields so i need to always check the value (prop ?? 0) , but that is only a problem when using with TypeScript, if I was only using JS I could just ignore this check.

If you thing passing null or undefined is not ideal, then maybe adding a warning log would alleviate the problem, something like 'you passed an undefined value but we used 0 instead'

scurker commented 1 year ago

There is an errorOnInvalid option if you want to catch a runtime error, but of course that doesn't help you in typescript land:

https://currency.js.org/#erroroninvalid-default-false

currency(undefined, { errorOnInvalid: true }); // throws an error

I think I have a little better understanding of where you're coming from, it technically is allowed from javascript - so that does seem like something we might want to consider making more loose in typescript. Let me think about what the implications of that change might be.