5

I have read that it's possible to add Extension Methods to types in TypeScript, however having a little trouble applying this to built-in type Number.

Here's some code:

File A: NumberExtensions.ts

// tslint:disable-next-line:class-name interface-name
export interface Number {
    isBigNumber(value: number): boolean;
}
// @ts-ignore
Number.prototype.isBigNumber = (value: number) => {
    return value > 100000;
};

File B: Uses the above

import { Number } from "./NumberExtensions";

foo() {
    const aBigNumber: number = 1000000000;

    // Errors here TS2339: Property 'isBigNumber' does not exist on type 'number'.
    if (aBigNumber.isBigNumber()) {
        console.log("It's a big number!");
    }
}

Is my declaration and usage of TypeScript extension methods correct?

Dr. Andrew Burnett-Thompson
  • 20,980
  • 8
  • 88
  • 178
  • 1
    Does this answer your question? https://stackoverflow.com/questions/58265985/extending-built-in-types-in-typescript (basically, put the interface extension in a `*.d.ts` file somewhere) – Alex Wayne Feb 14 '20 at 18:43
  • Does this answer your question? [How to create an extension method in TypeScript for 'Date' data type](https://stackoverflow.com/questions/38434337/how-to-create-an-extension-method-in-typescript-for-date-data-type) – Michael Freidgeim Jul 26 '21 at 22:05

1 Answers1

7

Since you define the augmentation in a file that is a module you will need to add the augmentation declaration in a declare global:


export { }
declare global {
    export interface Number {
        isBigNumber(): boolean;
    }
}
Number.prototype.isBigNumber = function (this: number)  {
    return this > 100000;
};

function foo() {
    const aBigNumber: number = 1000000000;

    // Errors here TS2339: Property 'isBigNumber' does not exist on type 'number'.
    if (aBigNumber.isBigNumber()) {
        console.log("It's a big number!");
    }
}



Playground Link

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • 1
    OK. This works, but I don't quite understand why (Javascript not my forte). Nevertheless I've got it working with export / declare global / number.prototype in one file, and the second file just has `import ./NumberExtensions". Thank you for help! – Dr. Andrew Burnett-Thompson Feb 14 '20 at 19:05