Tips for utilizing enum types in Typescript

My goal is to design a Question class that requires various types of responses for different scenarios. These responses can be in the form of a DoAnswer (e.g. "run") or a CheckAnswer (e.g. "check the clock"). I have created separate enums for these response types since there are only a limited number of possible actions and checks in my specific case, each needing a unique name and display string, making enums the ideal choice. Now, I am looking for a way to store the expected answer type for each question.

I had considered using something like answerType: enum;, but this approach does not work as an enum cannot be used as a value type. In Java, you could use Class<?> answerType, but I am unsure how to achieve similar functionality in TypeScript.

The reason behind needing this information is that I want to determine the correct answer based on the expected type for a given question, like so:

this.correctAnswers: DoAnswer[] | CheckAnswer[];

if(answerType is DoAnswer) {
  this.correctAnswers = answerService.calculateCorrectDoAnswers();
  // Here, answerService retrieves possibleAnswers and situationInQuestion
}

It's possible that I may be misunderstanding some key concepts, but at the moment, I am unable to see a more effective solution.

Answer №1

Enumerate

export enum QuestionList {
  ToAnswer = 'execute',
  VerifyAnswer = 'inspect the time'
};

Data Type

export type AnswerType = QuestionList.ToAnswer | QuestionList.VerifyAnswer;

Module

checkResponse(answer: AnswerType): void {
    if (answer === 'execute') {
      console.log('run')
    }

    if (answer === 'inspect the time') {
      console.log('clock')
    }

    // The statement below won't compile as the value is not defined
    if (answer === 'something else') 
  }

UPDATE:

There may be other methods, but you could try it this way:

Data Types

export type ActionsToDo =
  | 'execute'
  | 'alert the authorities'
  | 'dial emergency services'
  | 'cry for help';

export type ChecksToPerform =
  | 'inspect clock'
  | 'examine weapon'
  | 'survey location'
  | 'verify vehicles';

Response Utility

export const actionResponses = ['execute', 'alert the authorities', 'dial emergency services', 'cry for help'];
export const checkResponses = [
  'inspect clock',
  'examine weapon',
  'survey location',
  'verify vehicles',
];

Interactive Module

analyze(val: ActionsToDo | ChecksToPerform) {
    if (actionResponses.includes(val)) {
      // Action needed
    }

    if (checkResponses.includes(val)) {
      // Verification required
    }
  }

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

Encountering issues while incorporating decimal.js in TypeScript

Incorporating decimal.js into my TypeScript project has proven to be challenging. When attempting to run the code snippet below, I encounter the following error message: Cannot assign to read only property 'constructor' of object '[object Ob ...

Combining the output of two Observables through the CombineLatest method to generate a

I possess two separate collections of information: Data Model: taxControlReference [ { "providerId": "HE", "taxTables": { "STAT": [ 1 ] } }, ...

The styling of Primeng Carousel appears to be incorrect

After obtaining a copy of the Primeng v8 carousel component, I noticed that the output is quite different from what is displayed on its official website: <p-carousel dir="ltr" [value]="basicDataService.latestProducts" [numVisible]="4"> <ng-t ...

My browser is able to display the JSON response from an HTTP request, as well as the REST client, but

I am attempting to access my own endpoint on a subdomain managed by Nginx. I anticipate the request to fail and return a JSON payload structured like this: { "hasError": true, "data": null, "error": { " ...

Having trouble applying CSS styling to the div element

I'm new to CSS and struggling with aligning content within a div. Specifically, I can't get the actual price (striked off) to display next to the discounted price in the card - it keeps appearing underneath. Any ideas on how I can improve my CSS ...

The value currently displayed in the Angular 6 Material mat-selection-list

When using Angular Material2 mat-selection-list, we can determine if the current option is selected or not (as a Boolean). compnenent.html <mat-selection-list #shoes (selectionChange)="onSelection($event, shoes.selectedOptions)" > <mat-list-opt ...

Is there a way to position the label to the left side of the gauge?

Is there a way to position the zero number outside the gauge? I'm having trouble figuring out how to do it because the x & y options won't work since the plotLine's position keeps changing. The zero needs to move along with the plotLine and ...

Use ng2-select2 directive to connect a reactive form formControlName

For managing forms in my Angular 5 project, I have implemented Reactive Form. Within the form, I integrated ng2-select2 to create a dropdown. However, when attempting to bind formControlName to the <select2></select2> directive, an error is thr ...

Tips for utilizing a bootstrap navbar and dropdown in conjunction with angular 7

Attempting to click on the Dropdown link in the menu, but nothing happens. <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-a ...

Tips for accessing the app instance within a module in Nest.js

Currently, I am involved in a project that relies on multiple Nest repositories, approximately 4 in total. Each repository must integrate logging functionalities to monitor various events such as: Server lifecycle events Uncaught errors HTTP requests/resp ...

What is the best way to have an icon appear when a child component div is clicked, without it displaying on other similar divs?

Within my child component div, I have configured it to display information from an object located in the parent component. Initially, when the web app loads, it correctly shows three divs with names and messages retrieved from the created object. However, ...

Tips for successfully sending an interface to a generic function

Is there a way to pass an interface as a type to a generic function? I anticipate that the generic function will be expanded in the future. Perhaps the current code is not suitable for my problem? This piece of code is being duplicated across multiple fil ...

incongruity discovered during string conversion in HmacSHA256 within Ionic framework

I am facing an issue while trying to create a token in IONIC using the CryptoJS library. The signature generated by the method is different from what I expect. The expected signature is lLJuDJVb4DThZq/yP4fgYOk/14d3piOvlSuWEI/E7po= but the method provides m ...

Executing a service call test within my component's unit test

Is there a simple way to test if my service is being called? myComp.ts constructor(private myService: MyService) {} myFunction() { this.myService.someFunction(); } myTest.ts beforeEach(async(() => { TestBed.configureTestingModule({ imp ...

Utilizing regular expressions to search through a .md file in JavaScript/TS and returning null

I am currently using fs in JavaScript to read through a changelog.MD file. Here is the code snippet: const readFile = async (fileName: string) => { return promisify(fs.readFile)(filePath, 'utf8'); } Now I am reading my .md file with this fu ...

What could be causing the 404 error that occurs when attempting to post from an Angular2 application to PHP?

So far, all of the code below is functioning properly except for the PHP, which remains untested. The issue I am encountering is a 404 error when trying to access the PHP file on my localhost server. I have attempted using Lite-Server and XAMPP to rule ou ...

React - All subsequent variable declarations must be of the same type

Running webpack in my React application results in the following error message appearing 58 times across different variables: https://i.sstatic.net/uedR7.png Removing the @types directory did not resolve the issue and instead produced a new error message: ...

Utilizing Typescript Decorators to dynamically assign instance fields within a class for internal use

I am interested in delving into Typescript Decorators to enhance my coding skills. My primary objective is to emulate the functionality of @Slf4J from Project Lombok in Java using Typescript. The concept involves annotating/decorating a class with somethin ...

Error 16 occurred when attempting to ngUpgrade two different versions of Highcharts

After successfully upgrading my app to use ngUpgrade, I encountered an issue while trying to incorporate Highcharts. In the original version of the app, there was an older version of Highcharts designed for AngularJS. However, in the new hybrid app using ...

Organizing Firebase functions: Managing multiple functions and dependencies

Objective I aim to gain a deeper understanding of how the firebase CLI manages the deployment process for multiple firebase functions, each stored in different files, and how it handles dependencies that are specific to certain functions. Situation If I ...