While in the process of converting my code to TypeScript, I encountered a dilemma. I created a generic foreach function that can handle arrays and objects, with different types of callbacks for iteration. However, I'm unsure how to specify the type when it accepts multiple callback options. The function should be able to return either boolean or void, and accept callbacks of (any), (any, int), or (string, any) types. Here is what I have so far:
function foreach(obj: Array<any> | Object, func: (
((any) => boolean) |
((any) => void) |
((any, int) => boolean) |
((any, int) => void) |
((string, any) => boolean) |
((string, any) => void)
))
{
// if obj is an array ...
if(Object.prototype.toString.call(obj) === '[object Array]') {
// if using callback def1
if(func.length == 1) {
for(let i = 0; i < obj.length; i++) {
if(typeof func === "function") {
if(!func(obj[i])) break;
}
}
// if using callback def2
} else if(func.length == 2) {
for(let i = 0; i < obj.length; i++) {
if(!func(obj[i], i)) break;
}
}
// if obj is an object ...
} else if(Object.prototype.toString.call(obj) == '[object Object]') {
// if using callback def1
if(func.length == 1) {
for(let key in obj) {
if(!obj.hasOwnProperty(key)) continue;
if(!func(obj[key])) break;
}
// if using callback def3
} else if(func.length == 2) {
for(let key in obj) {
if(!obj.hasOwnProperty(key)) continue;
if(!func(key, obj[key])) break;
}
}
}
};