简体   繁体   中英

Extending Typescript number type

I want to add some function to number type. So I tried this code:

interface Number
{
    IsInRange(min: number, max: number):boolean;
}

Number.prototype.IsInRange = function(min: number, max: number): boolean
{
    if ((this >= min) && (this <= max)) return true;

    return false;
}

I put it in extensions.ts file in src/app/common (Is that correct place?)

The problem is that my code does not compile. I got:

Property 'IsInRange' does not exist on type 'number'.

But editor (Visual Studio Code) does not complain.

What am I doing wrong? I suppose that typescript number is not the same as Number interface.

Just have something like this among your utility functions:

export function isInRange(n: number, min: number, max: number): boolean {
  return n >= min && n <= max
}

Then use it like

const inRange = isInRange(4, 2, 10); // instead of 4.isInRange(2, 10)

数字接口应位于.ts文件的开头

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM