What role does enum play in typescript?

What is the purpose of an enum in typescript? If it's only meant to improve code readability, could we achieve the same result using constants?

enum Color {
Red = 1, Green = 2, Blue = 4
};


let obj1: Color = Color.Red;
obj1 = 100; // IDE does not show any error even though enums should accept specific values

If typechecking doesn't offer any advantages, couldn't we simplify it like this.

const BasicColor = {
    Red: 1,
    Green: 2,
    Blue: 4
};

let obj2 = BasicColor.Red;

Answer №1

Initially, consider the following:

const BasicColor = {
    Red: 1,
    Green: 2,
    Blue: 4
};

The values Red, Green, and Blue can be changed (unlike in an enum).


Enums offer several advantages:

  1. a defined set of known values (to prevent mistakes later on), each with...
  2. a specific set of literal-like types for each member, all provided by...
  3. a single named type that covers all values

To achieve this with a namespace, you would need to do something like this:

export namespace Color {
    export const Red = 1;
    export type Red = typeof Red;

    export const Green = 2;
    export type Green = 2;

    export const Blue = 3;
    export type Blue = typeof Blue;
}
export type Color = Color.Red | Color.Blue | Color.Green;

There is also some old behavior in TypeScript where assignment from any number to a numeric enum is allowed.

However, if you use a string enum, this behavior does not occur. Additionally, there are other features such as exhaustiveness checking that can be enabled with union enums:

enum E {
  Hello = "hello",
  Beautiful = "beautiful",
  World = "world"
}

function assertNever(x: never) {
  throw new Error("Unexpected value " + x);
}

declare var x: E;
switch (x) {
  case E.Hello:
  case E.Beautiful:
  case E.World:
    // perform actions...
    break;
  default: assertNever(x);
}

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

Tips for removing data from documents that include automatically generated IDs

In my Angular project, I am utilizing google-cloud-firestore as the database. To import Firestore, I used the code import { AngularFirestore } from '@angular/fire/firestore';. The following function is used to add data to the database: changeLev ...

Make the switch from TypeScript namespaces to ES2015 modules

After making adjustments to my TypeScript configuration, I am now encountering errors related to the no-namespace rule. Here is how my current setup involving namespaces looks like: Exporting classes within a namespace: namespace MyNamespace { export ...

An exploration on integrating a controller into an Angular directive class using Typescript

Here's the TypeScript code for an Angular directive class I've been working on: I'm wondering how I can incorporate a controller into this directive without creating a separate controller class. My goal is to write and inject the ISOLATE SC ...

The issue arises when TypeScript declarations contain conflicting variables across multiple dependencies

My current project uses .NET Core and ReactJS. Recently, I updated some packages to incorporate a new component in a .tsx file. Specifically, the version of @material-ui/core was updated from "@material-ui/core": "^3.0.3" to "@material-ui/core": "^4.1.3" i ...

Splitting a td tag into multiple columns dynamically with Angular

I am attempting to dynamically split the table element into separate columns. My desired layout should resemble this: https://i.sstatic.net/C81tg.png The values for name and surname are fixed at 1, but the values for subjects and grades can vary (there ma ...

Angular is patiently awaiting the completion of the subscription

Currently, I am in the process of developing a test application using Angular. The challenge arises when I attempt to retrieve data through a Get request and then return a value based on that data. The code snippet below outlines the scenario: public getN ...

Is it possible to use an Enum as a type in TypeScript?

Previously, I utilized an enum as a type because the code below is valid: enum Test { A, B, } let a: Test = Test.A However, when using it as the type for React state, my IDE displays an error: Type FetchState is not assignable to type SetStateActi ...

Form remains unchanged after manipulation in callback

Currently, I have a form with a list of editable objects (constants). Previously, it was possible to delete any object without confirmation. Now, I want to add a ngBootbox confirm step before the deletion process. In my .ts file, the code for deleting an ...

Ways to access nested keys in a TypeScript object as well as an array containing objects

As I develop a form generator, my goal is to achieve type safety for a nested object and an array of objects. Specifically, I want the 'name' property to correspond to the key of the respective object it belongs to. For instance, in the scenario ...

Issue with ngx-extended-pdf-viewer when using URL

I'm struggling to display my PDF file on a viewer using a URL in TypeScript. I am utilizing ngx-extended-pdf-viewer. Below is a snippet of my code with the URL replaced: <ngx-extended-pdf-viewer *ngIf="!isFirefox" [src]="'http://www.chi ...

Tips for preventing event propagation while clicking on a swiper.js image next/prev button within a bootstrap card

I have integrated ngx-swiper-wrapper within a bootstrap card as shown below, with a routerlink at the top. When I click anywhere on the card, it successfully routes to the designated page. However, I am facing an issue where I want to prevent routing if a ...

Script - Retrieve the content of the code element

I am currently developing an extension for VS Code that will enhance Skript syntax support. One challenge I am facing is the inability to select the body of the code block. Skript syntax includes various blocks such as commands, functions, and events, eac ...

SonarQube seems to be overlooking TypeScript files with the .ts extension

I'm currently setting up SonarQube on Jenkins for an Angular 2 project, but I'm facing an issue where Sonar isn't recognizing the TypeScript files with the .ts extension. Here's the current configuration: sonar.projectKey=App Name- An ...

What should be included in the types field of package.json for TypeScript libraries?

I'm finding it challenging to efficiently develop multiple typescript modules simultaneously with code navigation while ensuring the correct publishing method. What should I include in the "types" field of my package.json? Referring to: Typescriptlan ...

Angular 6: Harnessing the Power of RouterLinks

Can you navigate to a different section of another page using the defined ID without having to reload the entire page? ...

Troubleshooting Appium error management is ineffective

As a newcomer to appium, I might have made some mistakes. I'm encountering a problem with appium while using wdio and jasmine. it('wtf', (done) => { client.init().element('someName').getText() // ^ here ...

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

Having difficulty transforming ".jsx" to ".tsx" in a Next.js application while working with "getStaticProps"

My application utilizes the Printifull API and performs well with .jsx using the code snippet below: import axios from "axios"; export default function ApiTest(props) { console.log(props); return( <></> ( } export async ...

Navigating the complexities of integrating Rollup, ES modules, TypeScript, and JSX can be a challenging endeavor due to

Lately, I've been learning about the tools mentioned in the title. However, I've encountered some bumps along the way, so I'm turning to StackOverflow for help. My Requirements I need something like Rollup to pack my stuff For bare module ...

An error has occurred with mocha and ts-node unable to locate the local .d.ts file

This is the structure of my project: |_typetests | |_type.test.ts | | myproj.d.ts tsconfig.json Here is how my tsconfig.json file is configured: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "lib": ...