MikeMcl / bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
http://mikemcl.github.io/bignumber.js
MIT License
6.63k stars 743 forks source link

Type error #353

Closed hanakannzashi closed 1 year ago

hanakannzashi commented 1 year ago

I have a function like this

function handle(n: string, dp?: number) {
  return BigNumber(n).toFixed(dp); // type error, Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
}

This because the lib doesn't export raw function signature. Currently, two signatures allowd

toFixed(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string;
toFixed(): string;

I think we should export raw one

toFixed(decimalPlaces?: number, roundingMode?: BigNumber.RoundingMode): string;

A lot of functions have this issue

MikeMcl commented 1 year ago

The signatures are written this way to prevent undefined being able to be passed as the first argument and a rounding mode as the second argument, which would be a mistake.

shuckster commented 1 year ago

The typings are essentially considering arity as important.

This is slightly more strict than allowing a single undefined argument to be treated the same way as a call that takes zero arguments.

I think the easiest and perhaps clearest solution would be for you to put a typeof check in your handle function, branching with the appropriate call-signature depending on its result.