Is it possible to define a constant enum within a TypeScript class?

I am looking for a way to statically set an enum on my TypeScript class and be able to reference it both internally and externally by exporting the class. As I am new to TypeScript, I am unsure of the correct syntax for this. Below is some pseudo-code (which extends a Backbone Model) that outlines what I am trying to achieve...

class UnitModel extends Backbone.Model {
    static enum UNIT_STATUS {
        NOT_STARTED,
        STARTED,
        COMPLETED
    }

    defaults(): UnitInterface {
        return {
            status: UNIT_STATUS.NOT_STARTED
        };
    }


    isComplete(){
        return this.get("status") === UNIT_STATUS.COMPLETED;
    }

    complete(){
        this.set("status", UNIT_STATUS.COMPLETED);
    }
}

export = UnitModel;

I want to access the enum inside this class as well as outside the class, such as shown below:

import UnitModel = require('path/to/UnitModel');
alert(UnitModel.UNIT_STATUS.NOT_START);//I expect to see 0 since enums start at 0

Answer №1

To achieve this goal, it is important to declare the property outside of the class and then set it as a static attribute.

enum TASK_STATUS {
    NOT_INITIALIZED,
    IN_PROGRESS,
    DONE,
}

class TaskModel extends Backbone.Model {

    static TASK_STATUS = TASK_STATUS;

    isTaskComplete(){
        return this.get("status") === TASK_STATUS.DONE;
    }
}

export = TaskModel;

Answer №2

If you're looking to declare a namespace along with your class, one way to do it is by placing the enum inside the namespace itself. Here's an example of how you can achieve this:

class ItemModel extends Backbone.Model {
    defaults(): ItemInterface {
        return {
            status: ITEM_STATUS.PENDING
        };
    }

    isApproved(){
        return this.get("status") === ITEM_STATUS.APPROVED;
    }

    approve(){
        this.set("status", ITEM_STATUS.APPROVED);
    }
}

namespace ItemModel {
    export enum ITEM_STATUS {
        PENDING,
        APPROVED,
        REJECTED
    }
}

export = ItemModel;

After that, you can simply access your enum using ItemModel.ITEM_STATUS.

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

The intersection observer fails to detect any new elements or entries that are appended to the page after it has

When I press the "add section" button to create a new section, the intersection observer does not seem to observe it. Even when I try to run the observer again after pressing the button, it still doesn't work. I suspect that I need to reassign the `se ...

What is the best method for toggling a class to indicate the active tab in VueJS?

My goal is to set the active class on the first <li> tab by default, and then switch it to the second <li> tab when selected. I plan to use CSS to visually indicate which tab is currently active. If you would like to see the current output, ch ...

Routes inoperative as intended

When using a standard expressroute for this login, I have noticed that even if the req.body.password is incorrect, I am still getting redirected to '/login'. router.post('/student/login', (req, res) => { if (req.body.password === ...

Retrieve the additional navigation information using Angular's `getCurrentNavigation()

I need to pass data along with the route from one component to another and retrieve it in the other component's constructor: Passing data: this.router.navigate(['/coaches/list'], { state: { updateMessage: this.processMessage }, ...

Experiencing challenges in integrating fundamental Javascript elements on a chat page

My chat page skeleton is in place, but I'm facing challenges in connecting all the pieces. My goal is to send messages to the server whenever a user clicks 'send', and to update the displayed messages every 3 seconds. Any insights, tips, or ...

JavaScript Filtering Technique

Attempting to compose an array of names for a search output page The json arrangement looks like this: data = { "artists": [ { "artistName": "a" }, { "artistName": "b" }, { "artistName": "c" }, { "artistName": "d" }, { "artistName" ...

Tips for avoiding recursive error function calls in Angular 5

Is there a way to avoid repetitive function calls within a recursive function? Take a look at the following code snippet: loadFinalData(id, color){ this.data = this._test.getUrl(id, "white"); this.dataHover = this._test.getUrl(id, "blue"); } pri ...

My simple application is experiencing a problem where ComponentDidMount is not being invoked

I used a tool called create-react-app to build this simple application. Strangely, the ComponentDidMount method is never getting invoked. import React, { Component } from "react"; class App extends Component { componentDidMount() { console.log("M ...

Ion-List seamlessly integrates with both ion-tabs and ion-nav components, creating a cohesive and dynamic user interface

On my homepage, there is an ion-list. Sometimes (not every time), when I select an item in this list or navigate to the register page using "this.app.getRootNav().push("ClienteCadastroPage")", and then select an input in the registerPage or descriptionPage ...

Istanbul provides me with a thorough analysis, yet it always seems to conclude with an error

Currently, I am experimenting with a basic application (found in the Mocha tutorial code available at ) to troubleshoot why Istanbul is giving me trouble. The issue is that Istanbul successfully generates a coverage summary but then throws an error for unk ...

Dynamically assigning anchor tags to call JavaScript functions

Creating a list dynamically, full of <span class="infa9span"><img src="/csm/view/include/images/foldericon.png"/><a id="infa9Service">'+servicename+'</a><br/></span> tags. This list is then appended to a div. ...

Storing user information in Angular after login and implementing JWT authentication

Is it advisable to save any user information other than JWT in local storage or cookies after a successful login? (The user profile object is already saved and encrypted in the JWT payload sub-part.) I need the user profile object ready before initializing ...

Ways to verify the presence of users in the Database

I have successfully retrieved the data with the code below, but I am encountering issues with my script's if and else statements. Any tips or advice on how to improve this functionality? server.post('/like', (req, res,next) => { var ...

Content within a Row of a Data Table

Hello! I am just starting to learn JavaScript and jQuery. Can you help me with an issue I am experiencing? Basically, I have a table and I need to identify which tr contains a td with the text "Weekly", "Daily", or "Monthly". Once I locate that specific t ...

analyzing strings by comparing their characters to another string

In a scenario where I have two strings; let's call them string a="a-b-c" and string b="a-b". I am looking to determine whether every letter in string b is present within string a. ...

The width values in the array are constantly shifting upon refreshing

Would it be possible to create an array called slide_widths, which will contain the widths of all the .slide elements? $( document ).ready(function() { var $slider = $('.slider ul'); var slider_width = $slider.width(); var $slides = $(&apo ...

Transform string enum type into a union type comprising enum values

Is there a way to obtain a union type from a typescript string enum? enum MyEnum { A = 'a', // The values are different from the keys, so keyof will not provide a solution. B = 'b', } When working with an enum type like the one sh ...

My attempts to utilize the local storage key have been unsuccessful in storing my todo list. I am uncertain where the issue lies within my code

I've been working on a Todo List with local storage in React, but I'm running into an issue. It seems that my todos aren't getting stored properly and are disappearing every time the page refreshes. I need to figure out what's causing t ...

Issue with Bootstrap carousel: image protrudes past boundaries of parent container

Struggling with setting up a bootstrap carousel on my page. I want the image to extend beyond the parent div, positioned at the bottom rather than the top. How can I achieve this without disrupting the default carousel behavior? Here's a sketch of how ...

Show categories that consist solely of images

I created a photo gallery with different categories. My goal is to only show the categories that have photos in them. Within my three categories - "new", "old", and "try" - only new and old actually contain images. The issue I'm facing is that all t ...