我正在转换一些我用于打字的东西,而且我有点遗憾。我做了一个通用的foreach函数,它接受数组和对象,并采用几种不同类型的回调来处理迭代。但是,如果接受几个不同的回调函数,我不知道如何指定类型。我需要能够从函数返回布尔值或无效,并且它应该能够传入(any),(any,int)或(string,any)。这是我到目前为止所做的。Typescript:在工会中指定多个回调类型
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 callback def1
if(func.length == 1) { // error: property length does not exist on type 'any[] | Object'
for(let i = 0; i < obj.length; i++) {
if(typeof func === "function") {
if(!func(obj[i])) break; // error: Cannot invoke an expression whose type lacks a call signature
}
}
// if callback def2
} else if(func.length == 2) { // error: property length does not exist on type 'any[] | Object'
for(let i = 0; i < obj.length; i++) {
if(!func(obj[i], i)) break; // error: Cannot invoke an expression whose type lacks a call signature
}
}
// if obj is an object ...
} else if(Object.prototype.toString.call(obj) == '[object Object]') {
// if callback def1
if(func.length == 1) {
for(let key in obj) {
if(!obj.hasOwnProperty(key)) continue;
if(!func(obj[key])) break; // error: Cannot invoke an expression whose type lacks a call signature
}
// if callback def3
} else if(func.length == 2) {
for(let key in obj) {
if(!obj.hasOwnProperty(key)) continue;
if(!func(key, obj[key])) break; // error: Cannot invoke an expression whose type lacks a call signature
}
}
}
};
@SantiagoHernándezfunc.length是javascript函数的一个属性,它是该函数的参数数量。这是我最初区分原始JavaScript中的函数签名的方式。问题是我该如何在打字稿中做到这一点:\ – FatalCatharsis