Add a `Big.nullable(value)` method
sparebytes opened this issue · comments
Franklin Davenport commented
I appreciate that Big(x)
throws when x is null/undefined but there are times I know I'm working with a value that may be nullable and want to fail gracefully. Big.nullable(value)
makes it a bit easier to work with javascript's new null coalescing and optional chaining operators.
// simple case - not a huge benefit
return x == null ? Big(x).toFixed(2) : "Not set"
return Big.nullable(x)?.toFixed(2) ?? "Not set
// with optional chaining
return data?.user.rating == null ? Big.nullable(data.user.rating) .toFixed(2): "N/A";
return Big.nullable(data?.user.rating)?.toFixed(2) ?? "N/A";
See also #32
Michael M commented
If I am understanding you correctly, then the implementation would just be
Big.nullable = x => x == null ? x : Big(x);
Yes?
Franklin Davenport commented
Exactly!
Franklin Davenport commented
The typescript def would look something like this
interface Big {
nullable(value: BigSource): Big;
nullable(value: null): null;
nullable(value: undefined): undefined;
}
Edit: I lied, Typescript won't spread the overloads as I thought.
interface Big {
nullable(value: BigSource | null | undefined): Big | null | undefined;
}