jeudi 14 septembre 2017

Create typescript extension for array of particular class type

I know that i can create a basic Array extension, something like this, which works on all arrays, no matter what the type is within that array.

export {};

declare global {
    interface Array<T> {
        isEmpty(): boolean;
    }
}

// determines if an array is empty, or if the contents of the items in the array are empty
Array.prototype.isEmpty = function() {
    if (this.length == 0) {
        return true;
    } else {
        return this.some((c) => c != null && c != '');
    }
};

But i would like to create an extension for an array that only contains a particular object? I have tried this, but gives error

import { MyObject } from './my-object';

export {};

declare global {
    interface Array<MyObject> {
        isEmpty(): boolean;
    }
}

// determines if an array is empty, or if the contents of the items in the array are empty
Array.prototype.isEmpty = function() {
    if (this.length == 0) {
        return true;
    } else {
        return this.some((c) => c != null && c != '');
    }
};

I have tried to find out by looking here but i cannot seem to figure out the correct syntax.

Any help much appreciated :)




Aucun commentaire:

Enregistrer un commentaire