Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to correctly type an array function?

Let’s say that I have a custom function that I’ve written that loops over an array:

function find(array, callback, context) {

    const {
        length
    } = array;
    let index = 0;

    while (index < length) {

        if (callback.call(context, array[index], index, array)) {
            return index;
        }

        index += 1;

    }

    return -1;

}

Let’s further say that I want to properly type it using TypeScript:

function find(
    array: ArrayLike<any>,
    callback: (this: typeof context, item: any, index: number, array: ArrayLike<any>) => boolean,
    context?: any
) {
    // ...
}

Is there a better way to describe the parameters? I’d like to be able to say that the item parameter in the callback has the same type as the array items (although the actual type doesn’t matter). I’d also like to be able to say that both array references are the same thing.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You shoud use a generic parameter:

// TypeScript
function find<T>(
    array: ArrayLike<T>,
    callback: (this: typeof context, item: T, index: number, array: ArrayLike<T>) => boolean,
    context?: any
) {
    // ...
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading