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

Creating and utilizing multi-module NPM packages written in Typescript: A comprehensive guide

For a while now, I've been quite at ease creating and utilizing NPM packages with Typescript. However, these packages have typically been provided and consumed as a single module. Now, I'm interested in publishing packages that contain more than ...

Exploring Angular 4 with the power of Rangy modules

I've recently started working with Angular 4 and decided to create a basic app by forking the Angular quickstart. Now, I'm facing a challenge as I try to incorporate Rangy into my project. In my package.json, the dependencies are listed as follo ...

Having trouble with sending values to Angular 7 components' HTML pages

Struggling with a simple task and encountering an error: Code snippet below: app.component.html <div class="col-md-{{myvalue}}">stuff here</div> app.component.ts myvalue: string; ngOnInit() { this.myvalue('6'); } Seeing th ...

Angular's forEach function seems to be stuck and not loop

I'm attempting to cycle through a list of objects in my Angular/Typescript code, but it's not working as expected. Here is the code snippet: businessList: RemoteDataSet<BusinessModel>; businessModel: BusinessModel; this.businessList.forE ...

Sending template reference from one Angular component to another

I have a main grid component that includes smaller grid-item components. The majority of these grid items navigate to a specific route when clicked. However, there is one particular item that should open a modal window instead of navigating. Is there a wa ...

Setting up ReactJS and TypeScript in a fresh MVC5 project from scratch

After extensively trying out various tutorials, I have yet to successfully run a basic MVC5 project using TypeScript and ReactJS. For reference, I have created these projects from scratch in Visual Studio 2015 with .NET 4.6.1, using the ASP.NET Web Applic ...

Is Angular File API Support Compatible with HTML5?

When checking for HTML5 File API browser support in my code: private hasHtml5FileApiSupport; constructor(@Optional() @Inject(DOCUMENT) document: Document) { const w = document.defaultView; this.hasHtml5FileApiSupport = w.File && w.FileReader & ...

Using the `window` object in Jasmine with Angular, a mock can be created for testing purposes

In my current project, I have a function that I need to write unit tests for. Within this function, I am comparing the global objects window and parent using const isEqual = (window === parent). I am wondering what would be the most effective way to mock ...

Angular utilizes ZoneAwarePromise rather than a plain String output

I expected the giver code to return a string, but it is returning ZoneAwarePromise. Within the service: getCoveredPeriod() { let loanDetails = this.getLoanDetails().toPromise(); loanDetails.then((res: any) => { const coveredPeriodStart ...

Exploring the power of Typescript functions within a traditional VueJS project

TL;DR: How can I import and use a typescript module into my plain js Vue-Components? I have a Vue 2 (not yet 3) project. In this specific project, I have made the decision to refactor some of the code logic into ES modules for improved testability and reu ...

TypeScript requires that the `includes` function must have the same type parameter for both input and

When working with TypeScript, I've encountered an interesting dilemma regarding the use of the Array.Prototype.includes function. It seems that this function requires me to pass in the same type as in the original array, but isn't the purpose of ...

Error: Property 'xxx' is not a valid attribute for this type

Hey there! I recently converted my React Native JavaScript project into TypeScript and everything seems to be working fine. However, I'm encountering some warnings that I could use some help with. Specifically, I need assistance on how to properly pas ...

Error message in TypeScript: A dynamic property name must be a valid type such as 'string', 'number', 'symbol', or 'any'

Attempting to utilize the computer property name feature in my TypeScript code: import {camelCase} from "lodash"; const camelizeKeys = (obj:any):any => { if (Array.isArray(obj)) { return obj.map(v => camelizeKeys(v)); } else if (ob ...

The 'GoogleAuthProvider' property cannot be found on the 'AngularFireAuth' type

When attempting to sign in with Google using 'AngularFireAuth', I encountered an error. Here is the code snippet from my auth.service.ts file: import { Injectable } from '@angular/core'; import { first } from 'rxjs/operators'; ...

Combining types with additional features

Is it possible to configure the TypeScript compiler to generate an error when a function is called with an argument that can belong to both cases in a union type? For example: interface Name { name: string } interface Email { email: string } type ...

Listening to events on the iterative variable of NgFor directive in Angular 2

Angular2 has been my latest exploration in solving a unique data binding challenge. In my UI, I've presented a javascript array of objects like a database recordset in an HTML table. Each row contains menus and inputs allowing users to modify the rec ...

Executing a series of imported functions from a TypeScript module

I'm developing a program that requires importing multiple functions from a separate file and executing them all to add their return values to an expected output or data transformation. It's part of a larger project where I need these functions to ...

Customize the text displayed in a dropdown menu in Angular Material based on the selection made

I am working with a multi-select dropdown menu that includes an option labeled "ALL" which, when selected, chooses all available options in the list. My goal is to display "ALL" in the view when this option is chosen or when the user manually selects all t ...

Expanding the capabilities of generic functions in TypeScript using type variables

When working with generics in TypeScript, it is often beneficial for a function that accepts generically-typed arguments to have knowledge of the type. There exists a standard approach to achieve this using named functions: interface TestInterface<T> ...

The argument provided needs to be a function, but instead, an object instance was received, not the original argument as expected

I originally had the following code: const util = require('util'); const exec = util.promisify(require('child_process').exec); But then I tried to refactor it like this: import * as exec from 'child_process'; const execPromis ...