R
R
Roman Khegay2021-03-26 07:09:06
typescript
Roman Khegay, 2021-03-26 07:09:06

How to add method to base Number in Typescript?

Angular app.
I'm trying to add a method to the Number type:

tsconfig.json:

...
"typeRoots": [
    "node_modules/@types",
    "types"
]
...


types/number.d.ts:
export {}

declare global {
    interface Number {
        isInt() :  boolean
    }
}


number.extension.ts:
Number.prototype.isInt = function() {
    return (Math.round(this) == this)
}


And, when I try to compile, I get errors:

Error: number.extensions.ts:16:18 - error TS2339: Property 'isInt' does not exist on type 'Number'.
    [ng] 16 Number.prototype.isInt = function() {
    [ng]                     ~~~~~
    [ng] Error: node_modules/typescript/lib/lib.es5.d.ts:395:5 - error TS2300: Duplicate identifier 'trimMiddle'.
    [ng] 395     trimMiddle: () => any;
    [ng]         ~~~~~~~~~~
    [ng] Error: node_modules/typescript/lib/lib.es5.d.ts:396:5 - error TS2411: Property 'anchor' of type '(name: string) => string' is not assignable to string index type '() => any'.
    [ng] 396     [x: string]: () => any;
    [ng]         ~~~~~~~~~~~~~~~~~~~~~~~
    [ng] Error: node_modules/typescript/lib/lib.es5.d.ts:396:5 - error TS2411: Property 'charAt' of type '(pos: number) => string' is not assignable to string index type '() => any'.
    [ng] 396     [x: string]: () => any;
    [ng]         ~~~~~~~~~~~~~~~~~~~~~~~
    [ng] Error: node_modules/typescript/lib/lib.es5.d.ts:396:5 - error TS2411: Property 'charCodeAt' of type '(index: number) => number' is not assignable to string index type '() => any'.
    [ng] 396     [x: string]: () => any;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Khegay, 2021-03-26
@khegay

As it turned out, everything is fine with my code.
For some unknown reason, the compiler cached it. I had to delete and reinstall.

E
eewynell, 2021-03-26
@eewynell

There is already a built-in isInteger method, why write your own, and even in the Number prototype?
https://developer.mozilla.org/en/docs/Web/JavaScript...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question