I have a NameValuePair-interface and I want to write a function which "reduces" a list of Name-Value-pairs to a string. In this case the function would make a query string, e.g.
?name=foo&age=10
out of the given Name-Value-Pairs.
export interface NameValuePair {
name: string,
value: any
};
export const nameValuePairsToString = (
pairs: NameValuePair[],
innerSeperator: string="=", outerSeperator: string="&",
startValue="?"
): string => (
pairs.reduce((acc: string, pair: NameValuePair, idx: number): string => {
const pairAsString = pair.name + innerSeperator + pair.value;
const tail = idx === 0
? pairAsString
: outerSeperator + pairAsString;
return acc + tail;
}), startValue);
TypeScript throws this error at the definition of the anonymous function passed to the reducer:
Argument of type '(acc: string, pair: NameValuePair, idx: number) => string' is not assignable to parameter of type '(previousValue: NameValuePair, currentValue: NameValuePair, currentIndex: number, array: NameValuePair[]) => NameValuePair'. Types of parameters 'acc' and 'previousValue' are incompatible. Type 'NameValuePair' is not assignable to type 'string'.ts(2345)
Is it not possible to reduce an array of one type (NameValuePair) to another type (string). I thought that was the whole point of reducers? In JavaScript I always did used Array.prototype.reduce
like that...
Is it not possible in TypeScript or what did I do wrong?
((
at the reduce. First param should be the previous Valueacc
, not a callable – k0pernikus