5

in the post of "Typescript extend String Static", I got the a few that we can extend existing baseclass of typescript, for example, add new method

interface StringConstructor {
   isNullOrEmpty(str:string):boolean;
}
String.isNullOrEmpty = (str:string) => !str;

it really does work. but for generic interface, I met problems. for example, I need to add new method contain() in Array. I use the following code:

   //1
    interface Array<T> {
        contain(item: T): boolean;
    }  
    //2
    ?????? = (item: T) => {
    // ....
        return true;
    };

after step1, in VS intellisense does and pop up contain method, but where can I do implement method?

1

1 Answer 1

7

As the definition in the interface is already bound to the generic constraint, in the implementation you can just treat it as any:

interface Array<T> {
    contain(item: T): boolean;
}  

Array.prototype.contain = function(item) {
    return this.some(obj => item == obj);
};

Also, do not use arrow functions for prototype methods, here's why:

interface Array<T> {
    fn(): void;
}

Array.prototype.fn = () => {
    console.log(this);
};

let a = [];
a.fn(); // Window

But:

Array.prototype.fn = function() {
    console.log(this);
};

let a = [];
a.fn(); // []

If you're targeting es5 or lower then it doesn't matter as the compiler translates arrow functions into regular ones, but if you will then switch to targeting es6 (and the arrow functions will persist) then your code will break and you won't understand why.

Sign up to request clarification or add additional context in comments.

6 Comments

hi Nitzan, thanks your answer... if implement it as a instance method, it should be the same as in .net framework. I found whether use arrow function or not, the intellisense hint the parameter item is any, and no array itself which must be used in method body.. any suggestion about get array in method body?
Is it supposed to be an instance method or a static method? It makes sense based on the signature you posted that it's an instance method. The item is what you're looking for inside the array no? If so, it is supposed to be any
I like to do it by instance method because I am .net developer..:-) my concern is in method body, I can not get array[], I need array[] and item which has been passed in to write contains logic...
The array is just this because you are adding this method to the Array object prototype. As in my example: return this.some(obj => item == obj). The this.some method is the Array.prototype.some method.
got it. all I do is based on vs intellisense, but it does not work here...thanks again Nitzan..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.