I'm trying to implement clamp for multiple number-ish types simultaneously like so:
import BigNumber from 'bignumber.js'
export const clamp = <T extends number | BigNumber>(min: typeof n, n: T, max: typeof n): T => {
if (isNumber(n)) {
return Math.max(min, Math.min(n, max)) as T
}
if (isBigNumber(n)) {
return BigNumber.max(min, BigNumber.min(n, max)) as T
}
}
const isNumber = (n: number | BigNumber): n is number => {
return typeof n === 'number'
}
const isBigNumber = (n: number | BigNumber): n is BigNumber => {
return n instanceof BigNumber
}
But code failes to compile with the following error:
TypeScript error in clamp.ts(5,21):
Argument of type 'number | BigNumber' is not assignable to parameter of type 'number'.
Type 'BigNumber' is not assignable to type 'number'. TS2345
3 | export const clamp = <T extends number | BigNumber>(min: typeof n, n: T, max: typeof n): T => {
4 | if (isNumber(n)) {
> 5 | return Math.max(min, Math.min(n, max)) as T
| ^
6 | }
7 |
8 | if (isBigNumber(n)) {
Shouldn't types of min and max be inferred as number on line 5? If not, how can one assure Typescript of correctness of types?