Creating an enum in TypeScript can be accomplished by using the enum

What transformations do enums undergo during runtime in the TypeScript environment?

Fruit.ts

enum Fruit {APPLE, ORANGE};

main.ts

let basket = [Fruit.APPLE, Fruit.ORANGE];
console.log(basket);

The resulting main.js file remains identical to the .ts version, but this may not be feasible.

Answer №1

Here is the JavaScript code for that logic:

// Fruit.js
var Fruit;
(function (Fruit) {
    Fruit[Fruit["APPLE"] = 0] = "APPLE";
    Fruit[Fruit["ORANGE"] = 1] = "ORANGE";
})(Fruit || (Fruit = {}));

// main.js
var bowl = [Fruit.APPLE, Fruit.ORANGE];
console.log(bowl);

If you wish to optimize, consider using a const enum:

const enum Fruit {APPLE, ORANGE};

This approach will directly inline the values of the enum in the JavaScript code:

// Fruit.js: no content, as the values are directly used in main.js

// main.js
var bowl = [0 /* APPLE */, 1 /* ORANGE */];
console.log(bowl);

Using a const enum eliminates unnecessary JS generated from regular enums.

Answer №2

If you plan on utilizing the Fruit enum outside of the fruit.ts file, it's necessary to export it...

export enum Fruit {APPLE, ORANGE};

Then, in another file where you want to access it, you must reference it like this...

import {Fruit} from './fruit';
var fruitBasket = [Fruit.APPLE, Fruit.ORANGE];
// I must say, calling it a "fruitBasket" is quite fitting

Additionally, to use the import functionality, you need to specify a module type in tsconfig.json (or through command line arguments)

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 functionality of the Auth0 Logout feature has ceased to work properly following the

Previously, the code worked flawlessly on Angular version 14. However, after updating to version 17 due to persistent dependency issues, a problem arose. logout(): void { sessionStorage.clear(); this.auth.logout({ returnTo: window.location.origin } ...

shared interfaces in a complete javascript application

In the past, I have typically used different languages for front-end and back-end development. But now, I want to explore the benefits of using JavaScript/TypeScript on both sides so that I can have key data models defined in one central location for both ...

Angular 2 partial static routing parameters with customizable features

Can an angular 2 routing configuration include a partial-static parameter? Currently, I am using a classic parameter setup like this: const routes: Routes = [ { path: ':type/fine.html', pathMatch: 'full', redirectTo: &ap ...

Struggling to extract specific information from a json array using Angular, my current approach is only retrieving a portion of the required data

My JSON structure is as shown in the image below: https://i.stack.imgur.com/5M6aC.png This is my current approach: createUIListElements(){ xml2js.parseString(this.xml, (err, result) => { console.log(result); this.uiListElement = result[ ...

Regular pattern with Kubernetes cluster endpoint utilizing either IP address or fully qualified domain name

In my Angular/typescript project, I am working on building a regex for a cluster endpoint that includes an IP address or hostname (FQDN) in a URL format. For instance: Example 1 - 10.210.163.246/k8s/clusters/c-m-vftt4j5q Example 2 - fg380g9-32-vip3-ocs.s ...

Error Encountered: RSA Key Pairs Invalid Signature for JSON Web Token (JWT)

I am facing an issue with my Node.js application (version 20.5.1) regarding the verification of JSON Web Tokens (JWT) using RSA key pairs. The specific error message I am encountering is: [16:39:56.959] FATAL (26460): invalid signature err: { "type& ...

Investigating TypeScript Bugs in Visual Studio Code

As I navigate through various sources, I notice that there is a plethora of information available on older versions of VSCode (v1.16.1 - the most recent version at the time of writing) or deprecated attributes in the launch.json file. I have experimented ...

Mistakes that occur while trying to expand a base class to implement CRUD functionality

Creating a base class in TypeScript for a node.js application to be extended by all entities/objects for CRUD operations is my current challenge. The base class implementation looks like this: export class Base { Model: any; constructor(modelName ...

Exploring the distinction between "() => void" and "() => {}" in programming

Exploring TS types, I defined the following: type type1 = () => {} type type2 = () => void Then, I created variables using these types: const customType1: type1 = () => { } const customType2: type2 = () => { } The issue surfaced as "Type ...

What is the best way to arrange an array of objects in a descending order in Angular?

private sumArray : any = []; private sortedArray : any = []; private arr1 =['3','2','1']; private arr2 = ['5','7','9','8']; constructor(){} ngOnInit(){ this.sumArray = ...

Killing the command prompt in Typescript: A step-by-step guide

Is there a way to completely close the cmd where the typescript file is running but unable to do so? How can this be achieved? console.log('This ts file must be terminate itself'); let asdef = process.pid; let asdeff = process.ppid; const {exe ...

Synchronizing Form Data in Angular 5: Pass and Populate Dropdowns between Components

I have developed a unique form (material dialog modal) that allows users to create an account. When the user clicks on the Register button, their created account should appear in a dropdown menu without redirecting or reloading the current page. I am facin ...

Creating Angular models for complex nested JSON structures

I'm a beginner with Angular and I'm dealing with nested API responses from a Strapi application. I've set up a model using interfaces, but I'm having trouble accessing attributes from the product model when trying to access product data ...

Using Typescript to set the image source from a pipe

I've been working on creating a custom pipe similar to the code below: @Pipe({ name: 'imagePipe' }) @Injectable() export class ImagePipe { constructor(public someService: SomeService, public storage: Storage) { } transform(value: ...

Leveraging IntersectionObserver to identify the video in view on the screen

Our Objective I aim to implement a swipe functionality for videos where the URL changes dynamically based on the ID of the currently displayed video. Challenges Faced Although I managed to achieve this with code, there is an issue where the screen flashe ...

"Converting array into a string in TypeScript/Javascript, but unable to perform operations

After generating a string with the correct structure that includes an array, I am able to navigate through the JSON on sites like However, when attempting to access the array, it turns out that the array itself is null. Here is the scenario: Firstly, th ...

What is the best way to refresh a personalized form element using Angular?

I have developed a custom form control with validation that utilizes a standalone FormControl to manage the value and perform certain validations. Is there a method in Angular to reset the inner FormControl when the control is being reset from another For ...

Troubleshooting Problem in Angular 6: Difficulty in presenting data using *ngFor directive (data remains invisible)

I came across a dataset that resembles the following: Within my app.component.html, I have written this code snippet: <ul> <li *ngFor="let data of myData">{{data.id}}</li> </ul> However, when I execute this code, it only displa ...

An unusual problem encountered while working with NextJS and NextAuth

In my NextJS authentication setup, I am using a custom token provider/service as outlined in this guide. The code structure is as follows: async function refreshAccessToken(authToken: AuthToken) { try { const tokenResponse = await AuthApi.refre ...

Understanding TypeScript's ability to infer types in generics

Exploring the world of TypeScript through a robustly typed system for REST requests. Let's dive into the code: This type is used to establish the connection between routes and their respective object types: export interface RoutesMapping { api1: ...