Contrasting the utilization of `typeof` with a constant and `enum` in TypeScript

Can you explain the distinction between using typeof with a constant and an enum in TypeScript?

For example:

const TYPE_A = 'a'
const TYPE_B = 'b'
type MyType =
  | typeof TYPE_A
  | typeof TYPE_B

type Result = {
  name: string
  type: MyType
}

// and 

enum QuestionType {
  A = "a",
  B = "b",
}

type Result = {
  name: string
  type: MyType
}

I am interested in using the values "a" and "b" in multiple parts of the code. I was thinking about using typeof variable, but I'm not sure if that is the best approach.

I have also come across const enum, but I'm not clear on the differences between these options.

Answer №1

One key difference between the behaviors of typeof and enum lies in how they are handled during compilation and their accessibility at runtime.

While the compiler removes type information, standard enums are represented as an object at runtime. VLAZ also mentions that const enums may be inlined by the compiler.

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

Issue with Typescript in Material-UI's CardActionArea component attribute

The documentation for Material-ui's Buttons | Third party routing library explains the need to create an adapter to wrap a react-router-dom/Link component in a Button. Interestingly, attempting the same with a CardActionArea (which is labeled as a Bas ...

Dynamically setting the IMG SRC attribute with the base64 result of a FileReader for file input

Looking for a little guidance on something new, I'll keep it brief because I'm sure it's just some small detail I'm overlooking... Starting with an image like this, where currentImage is the initial existing image path; <img src="{ ...

What is the process for incorporating buttons into an Angular mat-table?

I have successfully utilized Angular mat-table to showcase data retrieved from a database: view the image description here <table mat-table [dataSource]="UserDataSourceFilters" class="mat-elevation-z1 mt-5"> <ng-co ...

Transforming JSON keys in Angular

As a newcomer to angular and API integration, I am facing an issue with ngCharts in my project. The chart specifically requires the keys names in JSON to be "value" and "name", but the API I am using provides keys named "count" and "label". Is there a way ...

The compilation of angular-cli version 25.5 encountered an error during module build

Issue Upon upgrading angular-cli from 22.1 to 25.5 (installing angular-cli@latest) and angular from version 2.2.3 to 2.3.1, the following problem occurred: ERROR in ./src/app/app.module.ts Module build failed: TypeError: Cannot read property 'text&a ...

Showcasing an input field once a specific button is pressed in an Angular application

When triggered, I am looking for a blank panel that will display a text box within the same panel. This functionality should be implemented using Angular. ...

"Encountering issue with auto-import suggestions failing to appear in VS Code version 1.88.0

After installing the necessary libraries for MUI, I encountered an issue where basic components like Typography were not showing up in intellisense. Instead, it was displaying @mui/icons-material. You can view screenshots below: https://i.stack.imgur.com/ ...

Performing Iterations in Angular 2 with Immutable.js (utilizing the *ngFor directive)

Struggling with Angular 2 and Immutable JS - having issues with a simple for-loop in my template. Tried both old and new syntax without success. <div *ngFor='#filter of filterArray' class='filter-row'> <div class='row-t ...

SonarQube alerting you to "Eliminate this unnecessary casting"

Can someone help me understand why SonarQube is flagging this error and suggest a resolution? The unnecessary cast should be removed. Promise.all([ this.customerViewCmr4tProvider.getData(activeNumber), this.customerBillManagementProvider.getData(ind ...

Encountering a Issue with Http module in Angular

When attempting to call my API using HttpModule, an error is being thrown upon starting the server (please refer to the screenshot). Error Image The error arises when I try to make a call to the API from the service using Http.post method. Here is my app ...

The field 'password' is not found in the 'User' array type

I'm encountering an issue with my Typescript code: Property 'password' does not exist on type 'User[]'.ts(2339). Do I need to create an interface or something similar? Thank you in advance. usersRouter.post("/", async ...

Compilation failure due to Typescript initialization issue

Encountering a TypeScript error in my IntelliJ-Idea 2017.1.1 IDE I have enabled JavaScript, NodeJS, and TypeScript Compiler. I have exhausted all solutions but the issue persists, perhaps I am missing something. Error: Initialization error (typescript ...

Angular - Execute function every 30 seconds while considering the duration of the function execution

In my Angular 7 application, I am utilizing RxJS to handle asynchronous operations. My goal is to retrieve a list of items from an API endpoint every 30 seconds. However, there are times when the request may take longer than expected, and I want to ensure ...

Tips on preventing the need to redeclare property types in React constructor with Typescript

Imagine having a class structured like this: class PeopleByTag extends React.Component<RouteComponentProps<{ tag: string }> In order to perform actions in the constructor, such as fetching data, you typically need to define a props parameter. Ho ...

Animating sprites using TypeScript

I've been tackling the development of a small Mario game lately. However, I'm facing some difficulty when it comes to animating sprites. For instance, I have a mario.gif file featuring running Mario (although he's not actually running in th ...

Incorporating Ionic Elements

I've been attempting to set a default segment as active in my app. After looking through other threads and questions, the solution appears to involve making changes in the segment js file located in the components folder. However, I can't seem t ...

Running Jest tests with TypeScript involves executing the tests twice: once for TypeScript files and once for JavaScript files

I’ve recently started writing tests using TypeScript and Jest, but I’m running into an issue where the tests are being executed twice – once for the TS files and then again for the compiled JS files. While the TypeScript tests are passing without an ...

There was an issue thrown during the afterAll function: Unable to access properties of undefined

Recently, I upgraded my Angular project from version 15 to 15.1 and encountered an error while running tests. To replicate the issue, I created a new Angular 15.1 project using the CLI and generated a service with similar semantics to the one causing probl ...

React JS displayed the string of /static/media/~ instead of rendering its markdown content

When I looked at the material UI blog template, I created my own blog app. I imported a markdown file using import post1 from './blog-posts/blog-post.1.md'; Next, I passed these properties to this component like so: <Markdown className=" ...

Tips for resolving the 'JSX is not defined no-undef' error post TypeScript 4.4.2 update

Upon upgrading to TypeScript 4.4.2 from TypeScript 3.8.2, I have encountered numerous errors such as error 'x' is not defined no-undef. For instance, one of the errors is error 'JSX' is not defined no-undef. Upon closer inspection, most ...