An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
April 1, 2022 01:11 am GMT
Original Link: https://dev.to/ku6ryo/avoiding-let-in-typescript-4ob4
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To