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.
>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
) {
// ...
}