Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewriting function in TypeScript

Tags:

typescript

I have the following (working) function in JavaScript:

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])
}

I'm trying to rewrite it using TypeScript as:

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])
}

but I'm getting the Type 'string' is not assignable to type 'number[]'. error, which I know refers to the accumulator, but don't know how to solve.

As per Rajesh's suggestion, changing the type of strArr to any solves the issue, but giving it the specific type I'm using with the function doesn't work; why?

like image 997
Bobby Wan-Kenobi Avatar asked Sep 15 '26 14:09

Bobby Wan-Kenobi


2 Answers

You can add a default case for your switch as others have suggested.

I would advise a second solution, which is to create a type for your input parameter to narrow the type:

type Direction = 'up' | 'down' | 'left' | 'right'

function solve(strArr: Direction[]) {
  return strArr.reduce(([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])
}

Play

like image 97
Roberto Zvjerković Avatar answered Sep 17 '26 06:09

Roberto Zvjerković


You should explicitly handle the default case in your switch:

function solve(strArr:string[]) {
  return strArr.reduce(([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]
      // maybe throw an error instead
      default: return [x, y];
    }
  }, [0,0])
}

Playground example

without the default case your reducer function returns the type: number[] | undefined

like image 33
TmTron Avatar answered Sep 17 '26 06:09

TmTron