Day 5 / 14 of building an MVP: Using Enums is easy, practical, and useful.
Using typescript, you can use something called enums. "Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums." Learn more about enums.
export enum Mode {
addField = "Add Field",
fieldSettings = "Field Settings",
formSettings = "Form Settings",
}
const [mode, setMode] = useState<Mode>(Mode.addField);
I am using string enums to specifically identify the field types in my useState hook. For example, with the enum, Modes, I can safely use Mode.addField
and know that is exactly what option I need.
You can see how typescript can auto-suggest what your state is expecting
If what you pass is not one of the strings you predefined in the Mode enum, it will throw an error.
So yeah, enums are cool.
Benefits of Enums
- Will let you know if you're passing something that is expected or not.
- Autosuggestion so you don't always have to type out the full string.
- Define once, use everywhere else.
I used enums for being able to specifically label what mode we are currently in using a string since there are three different modes. It was used in a useState hook. You can also use it anywhere where you need to input a specific string as it's value, and you want to make sure, you are inputting a string that's expected.
Example:
enum Players {
Lebron= "Lebron",
Jordan= "Jordan",
Kobe= "Kobe",
}
What if you want a response that's either those 3 players in a select input field
<select>
<option value={Players.Lebron}>{Players.Lebron}</option>
<option value={Players.Jordan}>{Players.Jordan}</option>
<option value={Players.Kobe}>{Players.Kobe}</option>
</select>
This can help prevent spelling errors such as or at least it will remind you that something is off when you push that off to state or to a database if you use enums there to check for some specific expectations.
<select>
<option value='LeBrun'>LeeBron</option>
<option value=Jordan>Gordan</option>
<option value=Kobe>Kobe</option>
</select>
But yeah, I hope I showed you the power of enums and what I learned from utilizing it. It's simple to use and the auto-suggestion it comes with it is awesome !!