I have a function in JavaScript that is working properly:
function solve(strArr) {
return strArr.reduce(function ([x, y], curr) {
switch (curr) {
case 'up': return [x, y + 1]
case 'down': return [x, y - 1]
case 'left': return [x - 1, y]
case 'right': return [x + 1, y]
}
}, [0, 0])
}
Now I am attempting to rewrite the function using TypeScript like this:
function solve(strArr: string[]): number[] {
return strArr.reduce(([x, y]: number[], curr: string) => {
switch (curr) {
case 'up': return [x, y + 1]
case 'down': return [x, y - 1]
case 'left': return [x - 1, y]
case 'right': return [x + 1, y]
}
}, [0,0])
}
However, I am encountering an error message
Type 'string' is not assignable to type 'number[]'
, specifically related to the accumulator. I am unsure of how to resolve this issue.
Following a suggestion from Rajesh on StackOverflow, changing the type of strArr
to any
does solve the error. However, providing it with the specific type used in the function does not work. I'm curious why this is the case.