Instead of leaving an Enum value as undefined, using a NONE value provides a more explicit

I've noticed this pattern in code a few times and it's got me thinking. When you check for undefined in a typescript enum, it can lead to unexpected behavior like the example below.

  enum DoSomething {
    VALUE1,
    VALUE2,
    VALUE3,
  }
  function doSomething(doSomething?: DoSomething): void {
    if (doSomething) {
      console.log('do something')
    } else {
      console.log('do nothing')
    }
  }
  doSomething(undefined) // -> do nothing
  doSomething(DoSomething.VALUE1) // -> do nothing
  doSomething(DoSomething.VALUE2) // -> do something

This issue arises because the VALUE1 of the enum is essentially 0. One solution could be to introduce a "NONE" value as the first position in the enum to avoid potential confusion with undefined values. What are your thoughts on this approach?

  enum DoSomething {
    NONE,
    VALUE1,
    VALUE2,
    VALUE3,
  }
  function doSomething(doSomething: DoSomething): void {
    if (doSomething) {
      console.log('do something')
    } else {
      console.log('do nothing')
    }
  }
  doSomething(DoSomething.NONE) // -> do nothing
  doSomething(DoSomething.VALUE1) // -> do something
  doSomething(DoSomething.VALUE2) // -> do something

While explicitly checking for undefined is always an option, overlooking the implications of if(0) can lead to debugging headaches, especially since it only fails for the first enum value. Any insights or suggestions on how to handle this scenario?

Answer №1

When it comes to coding conventions, they can vary depending on the company you are working for. Your example may be too abstract and could potentially violate a code convention that is not specific to any particular company.

As mentioned, in certain cases, checking for undefined values explicitly may be necessary, especially if it poses a real issue if someone were to pass such a value. Alternatively, one could argue that it is the responsibility of the individual passing the parameters to ensure they are valid, such as avoiding reserved keywords in this scenario.

In conclusion, while using enums like DoSomething can make sense in certain contexts, it ultimately depends on the situation and the guidelines you are following:

enum DoSomething {
    DoNot= 0,
    Do = 1,
    AlsoDo = 2,
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update a nested object key by concatenating key names with "." to create a string

Imagine having this specific object structure: var obj = { level1 :{ level2: { level3: { title: "champion" } } } } Now the goal is to update the title key using a provided string (note that it's a string, not an actua ...

Expanding the base class and incorporating a new interface

(Here is an example written using Typescript, but it applies to other cases as well) class IMyInterface { doC:(any) => any; } class Common { commonProperty:any; doA() { } doB() { } } class ClassA extends Common {} class Clas ...

Creating a ROT13 cipher in JavaScript

In my JS function, I need to handle a variable called i. My goal is to encode this variable using ROT13 before proceeding with the function. The challenge lies in decoding the variable and integrating it into the script. I came across a JavaScript implem ...

Java enumeration string comparison

Here's an example of how I've defined an enum: public enum ServerTask { HOOK_BEFORE_ALL_TASKS("Execute"), COPY_MASTER_AND_SNAPSHOT_TO_HISTORY("Copy master db"), PROCESS_CHECKIN_QUEUE("Process Check-In Queue"), ... } I am working with a string ...

Employing the filter or find technique to extract an element contained within a JSON data structure

Is it possible to retrieve one of these items using the filter or find method to search for a match within the fiberAgrupations array? I attempted the following: const landlineRate = this.monolineJsonRates[0].cambioCaudal.getAll() .filter(landlinedRat ...

What is the best way to manage the "open link in a new tab" action?

I am currently working on a project that involves displaying a series of resources on a web page. Each resource is stored as a record in a database with two fields: "url" and "visited." One issue I have encountered is that when a user clicks on a resource ...

Silly problem arising from the animate feature in jQuery

Apologies for my poor English. I am facing an issue with the animate function of jQuery in my code snippet. It seems to work fine at line 2, but it doesn't work at line 3. Can someone help me understand why? $('.opac').hover(function(){ ...

What is the best way to make a selected link stand out with a highlight?

I'm having an issue with the code below that is supposed to keep the selected link highlighted, but it only flashes the green color on click. Can someone help me figure out what's going wrong here? #sidebarContent a:active{ background-colo ...

Managing Recursive Promises: A Guide

function Authenticate() { this.invalidAccessToken = false; } Authenticate.prototype.checkTokenValidity = function (accessToken, refreshToken) { var token; var self = this; return new Promise(function (resolve, reject) { Authenticat ...

Javascript Rest for y moments

My website's JavaScript function uses AJAX to retrieve account information and open a modal for viewing and editing. Sometimes, the details don't update quickly enough in the database before the function collects them again, leading to discrepanc ...

Fill the second dropdown menu options based on the selection made in the first dropdown menu

I need assistance with dynamically populating my second drop-down menu based on the selection made in the first drop-down. Here are the steps I've taken so far: form.php - Utilizing javascript, I have set up a function to call getgeneral.php. The se ...

Magical Stylist - Eradicate Indicators while Preserving Labeling

Recently, I've been experimenting with the Google styling wizard in an effort to remove markers while retaining labels for businesses. My objective is to eliminate the marker icons but still display the text labels such as "Jimmy Johns," "Boone Saloon ...

Django: Error - < found where unexpected

Using a combination of Django and jQuery, I have implemented a file upload feature with AJAX. Everything seems to be working correctly - the files are successfully uploaded, reflected in the database, and stored on the server. However, upon completion of t ...

Unexpected issue with Ajax form submission when using the submitHandler function in Jquery

I am faced with the challenge of validating a form using the jQuery Validation Plugin and submitting data to a database without refreshing the page. Despite marking all fields in my form as required, the issue arises where empty fields are still submitted, ...

There was an issue with retrieving the image URL from the source, causing an error message to display: "

I encountered an error while trying to access my product. Here is the error message https://i.stack.imgur.com/fTmL0.png It seems that the image URL from the sanity database cannot be rendered, even though it worked fine in the tutorial I was following. I ...

Desiring the ability to retrieve a JSON response from a Laravel controller for use in my javascript code

I am trying to figure out the best way to fetch data from my Laravel controller and show it using JavaScript on a webpage. How should I approach this? Here is the code snippet of my controller and ajax call: var jq = jQuery.noConflict(); var id = jq(" ...

What is the best approach for retrieving values from dynamically repeated forms within a FormGroup using Typescript?

Hello and thank you for taking the time to read my question! I am currently working on an Ionic 3 app project. One of the features in this app involves a page that can have up to 200 identical forms, each containing an input field. You can see an example ...

Why is 'this.contains' not recognized as a function when I invoke it within another function?

While attempting to create a Graph and incorporating one method at a time, I encountered an issue. Specifically, after calling a.contains("cats"), I received the error '//TypeError: Cannot read property 'length' of undefined'. Could thi ...

Creating a cascading select box with two levels in PHP and MySQLExplanation on how to generate a two-tier connected

While I have successfully retrieved values from a MySQL database using a select box in PHP, I am struggling with implementing a two-level chained select box. Does anyone have any sample code or suggestions on how to achieve this? Thank you. ...

Securing routes in Angular without relying on LocalStorage or Cookies by implementing an Auth Guard

Currently, I am working on implementing an authentication guard in Angular. Instead of the conventional method of checking local storage or cookies to verify user authentication, I am utilizing API endpoints that respond with 200 OK if a httponly cookie co ...