0

I am trying to extend the number primitive in TypeScript by adding a clamp method. I tried doing this:

declare global {
    interface Number {
        clamp(min: number, max: number): number
    }
}

Number.prototype.clamp = function(min, max): number {
    return Math.min(Math.max(this, min), max);
};

At this point I expected to be able to use it on number variables, but my IDE (WebStorm 2021.1.3) was already pointing out issues:

TS2345: Argument of type 'Number' is not assignable to parameter of type 'number'. 'number' is a primitive, but 'Number' is a wrapper object. Prefer using 'number' when possible.

After reading this, I tried changing interface Number to interface number, but was met with TS2427: Interface name cannot be 'number'.

So I reverted my changes and slapped a @ts-ignore in the erroring line of the clamp implementation and tried to use it... however:

let x: number = 10;
x.clamp(0, 5);  // TS2339: Property 'clamp' does not exist on type 'number'.

What gives? How does one properly extend primitive types in TypeScript?

Khryus
  • 347
  • 3
  • 12
  • This is not recommended and a bad practice to modify. – xdeepakv Oct 17 '21 at 19:24
  • @xdeepakv I was missing the last step from this thread. Importing the file fixed my last issue, but I am still getting the first warning (TS2345). As for why this is not recommended and bad practice, can I ask why? What would be the best practice in this case? Just declare the function in a library as opposed to extending the primitive? – Khryus Oct 17 '21 at 19:27

0 Answers0