Tips for bringing in an enum from TypeScript?

I am working with a module defined in TypeScript that looks like this:

declare module MyTypes {

    export enum MyEnum {
        GOOD = 'Good',
        BAD = 'Bad',
        UNKNOWN = '-'
    }

   export interface MyType1 {
      myType1:string
   }

}

export default MyTypes;

In another file, I import it using the following code:

import MyTypes from '/my-types'
import MyType1 = MyTypes.MyType1
import MyEnum = MyTypes.MyEnum

However, when referencing MyEnum.GOOD in the code, Chrome throws an exception saying that MyTypes is not defined. What would be the correct way to import enums from modules in TypeScript?

Answer №1

When utilizing the declare keyword in TypeScript, it does not generate any JavaScript code; instead, it indicates that the code already exists. Interfaces function smoothly because they are removed at runtime. Conversely, enums have tangible string values such as "Good."

If you want everything to function correctly, simply delete the declare keyword.

module MyTypes {

    export enum MyEnum {
        GOOD = 'Good',
        BAD = 'Bad',
        UNKNOWN = '-'
    }

   export interface MyType1 {
      myType1:string
   }

}

export default MyTypes;

Just so you know, your JavaScript enum would appear like this:

export var MyEnum;
(function (MyEnum) {
    MyEnum["GOOD"] = "Good";
    MyEnum["BAD"] = "Bad";
    MyEnum["UNKNOWN"] = "-";
})(MyEnum || (MyEnum = {}));

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

What could be causing my date variable to reset unexpectedly within my map function?

Currently, I'm utilizing a tutorial to create a custom JavaScript calendar and integrating it into a React project You can find the functional JavaScript version in this jsfiddle import { useState, useRef, useMemo } from 'react' import type ...

Ways to transfer information from HTML form components to the Angular class

I am currently working with angular 9 and I have a requirement to connect data entered in HTML forms to the corresponding fields in my Angular class. Below is the structure of my Angular class: export interface MyData { field1: string, textArea1 ...

Utilizing Angular2 to scan barcodes

Im looking to create an application in asp.net 5 / Angular2 and I am encountering an issue with scanning barcodes. This is the TypeScript code for my component: @Component({ selector: 'barcode-scanner', templateUrl: 'app/scan.html& ...

Array filtering functions similarly to marketplace filtering tools

In order to make the filter function like a marketplace filter, I want to only see items related to the selected brand and status. For example: partners = [ 0:{ year: "2022" badge_status: "badge-success" sale_date: "01/07/2022&quo ...

You cannot assign type 'Node | null' to type 'Node' when attempting to loop through HTML elements in TypeScript

In my code, I am taking a raw Markdown string stored in 'markdownString' and using the marked.js library to convert it to HTML for display on a web browser. My goal is to extract all plain text values from the page and store them in an array of s ...

Steps to dynamically populate dropdown menus based on the selected options from other dropdown menus

I am working on a project that involves two dropdown menus. The options for the first dropdown menu are stored in a file called constant.ts. Depending on the selection made in the first dropdown, the options for the second dropdown will change accordingly. ...

What could be the reason for my Angular 2 app initializing twice?

Can someone help me figure out why my app is running the AppComponent code twice? I have a total of 5 files: main.ts: import { bootstrap } from '@angular/platform-browser-dynamic'; import { enableProdMode } from '@angular/core'; impor ...

Using Angular NgUpgrade to inject an AngularJS service into an Angular service results in an error message stating: Unhandled Promise rejection: Cannot read property 'get' of undefined; Zone:

I have noticed several similar issues on this platform, but none of the solutions seem to work for me. My understanding is that because our Ng2App is bootstrapped first, it does not have a reference to $injector yet. Consequently, when I attempt to use it ...

Mocha has difficulty compiling Typescript code on Windows operating system

In developing my nodejs module, I created several unit tests using Mocha and Chai. While these tests run smoothly on macOS, they encounter compilation issues on Windows, resulting in the following error: D:\projects\antlr4-graps>npm test > ...

The absence of a semicolon following the interface declaration is the issue

I am facing a slight issue with ESLint and Typescript, particularly regarding semicolons after declaring interfaces. Additionally, I utilize VSCode as my editor with automatic formatting upon saving. Below is the configuration in my .eslintrc.json file: ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

Angular 14: Deleting an item from a FormArray triggers unintended form submission due to Angular animation

After beginning to create animations for my app, I observed that deleting an element from a FormArray triggers a form submission. Custom form controls were developed using ControlValueAccessor, and certain FormGroups are passed through @Inputs. The animati ...

Transform Typescript into compiled css files without using any additional tools

Currently, I am working on a monorepo project where the main project relies on another project called components. When running the entire monorepo, the main project utilizes webpack.dev while the components project simply uses the TypeScript compiler. It l ...

Retrieve information from a URL to transmit to a different page in NextJS using Typescript and AppRouter

I'm struggling with transitioning from the Home page to the Detail page. I've successfully passed data to the URL from the Home screen, but I'm having trouble accessing it in the Detail screen. I'm working with NextJS ver 13, using Type ...

What is the best way to get my Discord bot to respond in "Embed" format using TypeScript?

I've been attempting to create a bot that responds with an embedded message when mentioned, but I'm running into some issues. Whenever I run this code snippet, it throws an error in my terminal and doesn't seem to do anything: client.on(&apo ...

Utilize knex.js and TypeScript to create queries with specific conditions

I am trying to create a dynamic query that will include a where clause based on whether the variables name and/or city are passed. While I couldn't find a specific method for this in the documentation, I attempted to add the where clauses directly to ...

Troubleshooting: Issues with APIGateway's Default Integration

I'm currently utilizing the AWS CDK to construct my API Gateway REST API My objective is to have my RestApi configured to automatically return an HTTP 404 error, so I set it up as follows: this.gateway = new apigw.RestApi(this, "Gateway", { ...

Combine two elements in an array

I am faced with a challenge in binding values from an Array. My goal is to display two values in a row, then the next two values in the following row, and so on. Unfortunately, I have been unable to achieve this using *ngFor. Any assistance would be greatl ...

How can I implement a feature in Angular where clicking the edit button loads a form (in a separate component) pre-populated with previous data, along with an update button for

Within the employee-list component, there is a table displaying a list of employees. This table includes an option to edit details. <button type="button" class="btn btn-primary" routerLink="../create-employee">Edit</b ...

Update the style dynamically in Angular using an ngFor directive and an array of data

Is there a way to dynamically set the width using data from an array in Angular? The usual approach doesn't seem to work. How can I solve this issue? <div *ngFor="let item of products"> <div [style.width.px]="item.size" class="Holiday"&g ...