Ekoar
Ekoar

Reputation: 481

how to extend method in typescript

I saw an article about extension method in typescript (https://medium.com/my-coding-life/extension-method-in-typescript-66d801488589) and try to implement my own extension method in a ts file.

alias.ts:

interface Array<T> {
  remove(item: any): void,
  draw(): any
};

Array.prototype.remove = function (item) {
  let id = this.indexOf(item);
  id !== false && this.splice(id, 1);
};

Array.prototype.draw = function () {
  return this[Math.floor(Math.random() * this.length)];
};

everything looks fine so far, However, it gives me errors after I imported momentJs. Anyone know what the problem is?

enter image description here

Upvotes: 0

Views: 240

Answers (1)

Phat Huynh
Phat Huynh

Reputation: 902

Try this

declare global {
    interface Array<T> {
        remove(item: any): void,
        draw(): any
    }
}

Array.prototype.remove = function (item) {
    let id = this.indexOf(item);
    id !== false && this.splice(id, 1);
};

Array.prototype.draw = function () {
    return this[Math.floor(Math.random() * this.length)];
};

Hope it helps

Upvotes: 3

Related Questions