-
Book Overview & Buying
-
Table Of Contents
Refactoring TypeScript
By :
In the following sections of this chapter, we are going to stick with the same example as the code snippet in the previous section. We'll improve it one step at a time.
Often, this is how you will approach refactoring: starting with the simplest refactoring. As your code becomes more complex or requires more TLC, then you can bring out the big guns.
Our scenario is a web application where we need to check some user permissions around editing a resource.
if(user.role === "admin"
&& user.active
&& user.permissions.some(p => p === "edit")) {
// Do stuff.
}
How can we make this more readable, understandable, less prone to bugs, and easier to maintain?
One of the quick wins you can get with these kinds of verbose conditionals is to start by moving each one into its own variable.
Let's start with this:
const isAdmin: boolean = user.role === "admin...
Change the font size
Change margin width
Change background colour