Is it possible to define a shared function for enums in TypeScript?

I have created an enumeration called VideoCategoryEnum:

enum VideoCategoryEnum {
  knowledge = 0,
  condition = 1,
  interview = 2,
  speech = 3,
  entertainment = 4,
  news = 5,
  advertisement = 6,
  others = 7,
}

I am looking to implement a shared method for all enums so that I can use the following code:

VideoCategoryEnum.tostring() // 'VideoCategoryEnum'

Is there a way to achieve this functionality? Thank you.

Answer №1

Typescript enhances Javascript by providing compile-time type checking. Enum types in Typescript are essentially mapped as objects, as explained in this helpful answer.

Adding a toString function to an enum type is a simple task. Just remember not to include the implementation in .d.ts files, as they will not be compiled into JavaScript.

Referring to the aforementioned answer link, your enum type would be transformed into:

var VideoCategoryEnum;
(function (VideoCategoryEnum) {
   VideoCategoryEnum[VideoCategoryEnum["knowledge"] = 0] = "knowledge";
   VideoCategoryEnum[VideoCategoryEnum["condition"] = 1] = "condition";
   // ...
})(VideoCategoryEnum || (VideoCategoryEnum = {}));
;

/* which would be equivalent to:
   VideoCategoryEnum = {
      "knowledge": 0,
      "condition": 1,
      ...
      "0": "knowledge",
      "1": "condition",
   }
*/
// as it's essentially an object, you can customize it as needed
// implement your own toString function here
VideoCategoryEnum.toString = function() { return 'VideoCategoryEnum'; };

Answer №2

Check out ts-nameof for the solution you need.

If you're using babel, there are a couple of options available, and one for tsc as well.

In the example provided above, you can see how it is used:

enum VideoCategoryEnum {
  knowledge = 0,
  condition = 1,
  interview = 2,
  speech = 3,
  entertainment = 4,
  news = 5,
  advertisement = 6,
  others = 7,
}

nameof(VideoCategoryEnum); // Returns 'VideoCategoryEnum'

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

Error: React js app has crashed. Currently waiting for file changes before restarting

I recently began using nodemon and started working on a small sample project. However, when I try to launch the server using sudo npm run dev, I encounter the following error: [nodemon] app crashed - waiting for file changes before starting... The error ...

I am facing a problem with React Hooks useRef where I am unable to retrieve the updated state value

Trying to use useRef with React hooks, I encountered an issue where the state of the child component changes when calling the setAccountVal method, but upon alerting the value it remains as "Ege". Any ideas on how to resolve this? import React, { useS ...

Having difficulty aligning ListItem to the right within a List

I am working with an array that contains objects which I need to display in ListItems of a List. My goal is to show these ListItems from the array Objects in a layout where odd numbers are on the left and even numbers are on the right. However, I am facing ...

Just a quick inquiry regarding adding new line characters in JSON to be used in

After encountering an issue with a JSON file in my JavaScript application where it would not print new lines when viewed on the console, I am at a loss for a solution. The contents of my JSON file are as follows: [ { "id": "71046" ...

Utilizing ESLint to Conditionally Import External Packages

I'm attempting to bring in a package and utilize it within my Vue application like so: import ExternalSamplePackage from 'external-sample-package' export default { directives: { ExternalSamplePackage } } Since I am in SSR mode, I want ...

Angular 5 does not allow function calls within decorators

I encountered an issue while building a Progressive Web App (PWA) from my Angular application. When running ng build --prod, I received the following error: ERROR in app\app.module.ts(108,64): Error during template compile of 'AppModule' Fu ...

The foundation of JSON and its structural encoding

Looking to deserialize JSON from Java, here's how it's done: Java jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(graphDTO); JSON "accounts" : [ { "name" : "1009427721", "value" : 16850.79, "children" : ...

Moving between different perspectives within a single-page backbone application

I am interested in incorporating dynamic transitions similar to the ones showcased on this website into a single-page backbone application. However, I am unsure of where to begin. Do I need to modify how I initialize my views (currently using a standard sw ...

`Misconceptions in understanding AngularJS directives`

I am currently working on a new app that includes both a header and main view, utilizing directives. At first, I had the directive in its own file but decided to relocate it into app.js in order to resolve an issue. Throughout this process, I have experim ...

Guide on implementing asyncWithLDProvider from Launch Darkly in your Next.js application

Launch Darkly provides an example (https://github.com/launchdarkly/react-client-sdk/blob/main/examples/async-provider/src/client/index.js) showcasing how to use asyncWithLDProvider in a React project (as shown below). However, I'm struggling to integr ...

Guide to developing a custom plugin for Nuxt.js

This is the content of my rpc.js plugin file: const { createBitcoinRpc } = require('@carnesen/bitcoin-rpc') const protocol = 'http' const rpcuser = 'root' const rpcpassword = 'toor' const host = '127.0.0.1&apo ...

What are some effective strategies for utilizing observables for handling http requests in an Angular application?

In my Angular application, I am retrieving data from APIs. Initially, my code in detail.component.ts looked like this: //code getData() { this.http.get(url1).subscribe(data1 => { /* code: apply certain filter to get a filtered array out */ t ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

Utilizing Mongoose Schema for CSV Import

My current task involves importing a large CSV file into a mongo DB, where the order of the values will determine the key for each entry in the database: Here is an example of the CSV file structure: 9,1557,358,286,Mutantville,4368,2358026,,M,0,0,0,1,0 9 ...

Is it possible to retrieve JSON data and display only the entries with positive values in an HTML

I am working on a project that involves fetching JSON API data and displaying it in an HTML table, but only for values above 10. Below is the code snippet along with my JavaScript. I specifically want to exclude negative values and only display positive v ...

The function that can be used in Ajax for setting

I'm currently utilizing Ajax to automatically submit a form when a key is pressed. After the form is submitted, the page displays the resulting information success: function (response){ $("#search_results<?php echo $HoursID ?>").html(response) ...

The Angular JavaScript page successfully compiles, yet displays only a blank screen

I am facing an issue with my Angular app where it compiles successfully, but the HTML page appears blank and my application is not displaying properly. I have encountered similar problems in the past which were often related to Imports, but this time I&apo ...

The rendering process in ag-grid is resulting in the service component initialized from an event to become null

Currently, I am utilizing ag-grid and need help understanding a specific issue. In my method for preparing GridOptions, I have set up an onCellValueChanged event that triggers a service component to access the database and populate the data. However, when ...

Just for laughs: "The react-redux context value seems to be playing hide and seek; make sure to wrap the component in a <Provider> for it to show up!"

I encountered an issue while attempting to run a basic Jest test on a form React component: ● <LoginForm /> › clicking the validate button › should display page title ...

Create a custom VueJS component by utilizing an npm package

Looking to navigate around X-frame restrictions? You can check out this npm package: https://www.npmjs.com/package/x-frame-bypass To make it work, include the following tag within your HTML: <iframe is="x-frame-bypass" src="https://example.org/">& ...