Avoiding `let` in TypeScript

Ryo Kuroyanagi - Apr 1 '22 - - Dev Community

I sometimes feel I am forced to use let instead of const in TypeScript even I want to use const to prevent reassignments.

When we use if or switch, there are cases that seems we need to use let. However, we do not have to use let actually.

const fruitNum: number = 0 // a number to represent a type of fruit
let fruitName: string = "Unknown"

switch(fruitNum) {
  case 0:
    fruitName = "Apple"
    break
  case 1:
    fruitName = "Banana"
    break
  default:
    break
}
Enter fullscreen mode Exit fullscreen mode

Instead of the above code, we may want to use a anonymous function to make fruitName a const.

const fruitNum: number = 0 // a number to represent a type of fruit
const fruitName: string = (() => {
  switch(fruitNum) {
    case 0:
      return "Apple"
    case 1:
      return "Banana"
    default:
      return "Unknown"
  }
})()
Enter fullscreen mode Exit fullscreen mode

Hope this makes your code more cleaner!

. . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player