I am a Senior Front-End Engineer at Perkbox, working within a large team of FE developers split over 5 projects. Alongside the day-to-day feature building and bug fixing, we are encouraged to try new techniques and practices to increase the quality of our work and our overall working practices.
Previously on this subject: Stateless and Stateful Components
This article assumes you already have at least a basic understanding of React, and ES6 syntax.
Before we were using TypeScript, we used variables such as
const KRAMER = “kramer" and exported these from a shareable file, which works fine and multiple developers can use these variables with no issues.
However, the issue came when using these variables if they are being passed into Components, functions or used in the state. Particularly this is noticeable if the developer wants to be strict with their PropTypes, functions, and the same with their state.
Of course, using
typeof within a function to fully ensure the explicit nature of that function would be beneficial, however for the most part that shouldn’t be necessary.
Whilst using these variables with PropTypes isn’t impossible, it can be impractical. Using them across multiple files means that when a new character value is added; i.e. if we wanted to add
Newman (we probably wouldn’t though, right?), multiple components may need to be updated, and so more often than not
PropTypes.string is used instead. Whilst more explicit, it can also be harder to read.
In contrast, with TypeScript setting the interface key to be an enum, this means it will always be up to date. In the example below, you can see how this is used when there is a select field with options made up of the values of the enum, but also how the initial state is managed, set and passed up to the parent, keeping everything in check across multiple components.
Similar to the migration of stateless/stateful components, the React itself doesn’t really change. What does change is what can and can not be passed into a Component, how those variables are managed, and how those variables are controlled/used when they are in the Component.
The goal of this is:
- Make code easier to maintain
- Make developing easier to collaborate
- Find bugs quicker
- Fix bugs quicker
If you start to take into account that these enums can be generated from GraphQL, Swagger, or a variety of other sources, it’s possible to see how the Front-End can easily be managed to match the Back-End with ease.
A little helper for converting an enum to an array: github.com/thomasparsons