这是我的功能签名:
sed '/'[:blank:]'/ c\ NO' inputfile.txt > outputfile.text
以下是我的称呼方式:
export type ReduceCallback<TVal,TAcc>
= (accumulator: TAcc, currentValue: TVal, currentIndex: number, array: TVal[]) => TAcc
export function reduceArray<TVal,TAcc>(
iterable: Iterable<TVal>,
callback: ReduceCallback<TVal,TAcc>,
initialValue: TAcc
): TAcc;
export function reduceArray<TVal>(
iterable: Iterable<TVal>,
callback: ReduceCallback<TVal,TVal>,
initialValue?: TVal
): TVal {
let arr = toArrayStrict(iterable);
if(initialValue === undefined) {
return arr.reduce(callback); // 2nd arg has to be fully omitted
}
return arr.reduce(callback, initialValue);
}
reduceArray([0,1,2,3], (acc, val) => acc + val)
抱怨:
TS2346:提供的参数与呼叫目标的任何签名都不匹配。
但我无法弄清楚原因。我的电话应该匹配第二个功能签名,不是吗?我在通话中省略了tsc
,所以它应该别无选择,只能匹配第二个签名。
initialValue
是[0,1,2,3]
,Iterable<number>
应该使用ReduceCallback
,这意味着ReduceCallback<number,number>
和acc
是数字。
有什么问题?
答案 0 :(得分:2)
你的重载语法有点不对劲。对于重载,您需要声明每个特定的重载。实际的函数头不算作声明。这意味着在您的情况下,您不幸地必须指定两次函数头:
// because I don't know what toArrayStrict is
declare function toArrayStrict<T>(it: Iterable<T>): T[];
export type ReduceCallback<TVal, TAcc>
= (accumulator: TAcc, currentValue: TVal, currentIndex: number, array: TVal[]) => TAcc
export function reduceArray<TVal,TAcc>(
iterable: Iterable<TVal>,
callback: ReduceCallback<TVal,TAcc>,
initialValue: TAcc
): TAcc;
// here we declare the second overload, which is just a duplicate of the actual function header
export function reduceArray<TVal>(
iterable: Iterable<TVal>,
callback: ReduceCallback<TVal, TVal>,
initialValue?: TVal
): TVal;
export function reduceArray<TVal>(
iterable: Iterable<TVal>,
callback: ReduceCallback<TVal,TVal>,
initialValue?: TVal
): TVal {
let arr = toArrayStrict(iterable);
if(initialValue === undefined) {
return arr.reduce(callback); // 2nd arg has to be fully omitted
}
return arr.reduce(callback, initialValue);
}
来源:https://www.typescriptlang.org/docs/handbook/functions.html(在底部)
答案 1 :(得分:1)
你有两个问题。首先,当你调用reduceArray时,它试图使用第一个重载,因为initialValue是非可选的。其次,您正在寻找的Array.reduce()的重载具有非可选的第二个参数。
reduce<U>(callbackfn: (previousValue: U, currentValue: T,
currentIndex: number, array: ReadonlyArray<T>) => U, initialValue: U): U;
该方法应该自动处理“首次通过”值,因此我简化了该部分。我还将toArrayStrict()
替换为Array.from()
,因为我无法弄清楚该方法是什么,但它似乎返回了一个数组类型。
export type ReduceCallback<TVal, TAcc> = (accumulator: TAcc, currentValue: TVal, currentIndex: number, array: Array<TVal>) => TAcc
export function reduceArray<TVal, TAcc>(
iterable: Iterable<TVal>,
callback: ReduceCallback<TVal, TAcc>,
initialValue?: TAcc
): TAcc;
export function reduceArray<TVal>(
iterable: Iterable<TVal>,
callback: ReduceCallback<TVal, TVal>,
initialValue?: TVal
): TVal
{
let arr = Array.from(iterable);
return arr.reduce(callback, initialValue);
}
let result = reduceArray([0, 1, 2, 3], (acc: number, val) => acc + val);
console.log(result);