Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 1, 2022 01:11 am GMT

Avoiding `let` in TypeScript

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 fruitlet fruitName: string = "Unknown"switch(fruitNum) {  case 0:    fruitName = "Apple"    break  case 1:    fruitName = "Banana"    break  default:    break}

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 fruitconst fruitName: string = (() => {  switch(fruitNum) {    case 0:      return "Apple"    case 1:      return "Banana"    default:      return "Unknown"  }})()

Hope this makes your code more cleaner!


Original Link: https://dev.to/ku6ryo/avoiding-let-in-typescript-4ob4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To