Stephan K.
Stephan K.

Reputation: 15702

Re-Write JavaScript function as class method? (TypeScript possible)

Given Code

var isEmptyArray = function (array) {
   if (typeof array !== 'undefined' && array.length > 0) {
}

Usage

isEmptyArray(myArray);

Wanted Result

How can I re-write above to be able to use:

myArray.isEmptyArray();

Upvotes: 1

Views: 61

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164137

Just javascript:

Array.prototype.isEmptyArray = function() {
    return this.length === 0;
}

Typescript:

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

Array.prototype.isEmptyArray = function() {
    return this.length === 0;
}

Edit

The above solution will work for all instances of Array, for example:

let a = [];
console.log(a.isEmptyArray()); // true
a.push(1);
console.log(a.isEmptyArray()); // false

You can create your own array class and then implement needed methods just there (without affecting other Array instances):

class MyArray<T> extends Array<T> {
    public isEmptyArray(): boolean {
        return this.length === 0;
    }
}

let a1 = [];
console.log(a1.isEmptyArray()); // Uncaught TypeError: a.isEmptyArray is not a function

let a2 = new MyArray<any>();
console.log(a2.isEmptyArray()); // true

This approach is good when you're using other js libraries which are not aware of the changes you've made in the Array prototype.

Upvotes: 4

Related Questions