Can one generate an enum based on a specific type?

I have a preference:

preference Preference = 'OptionA' | 'OptionB'

Is it feasible to generate an enumeration from this preference? For instance:

enumeration Enum = {
  OptionA,
  OptionB
}

I am uncertain about the feasibility of this. I came across a method to establish a type based on an enumeration, so perhaps this can also be achieved.

Appreciate any insights.

Answer №1

Runtime does not recognize Typescript types as they do not generate any runtime artifacts due to type erasure.

In contrast, Enums in Typescript are a standalone feature that is not merely a type-level extension of JavaScript.

Typescript types serve to describe and restrict the code statically, rather than vice versa. Creating a Type based on an Enum for type safety is logical, but the reverse does not hold true.

Consider this thought experiment: Can you envision a scenario where defining an Enum from a type is more appropriate than the opposite?

Keep in mind that an Enum implicitly defines its own type. As shown in the Typescript documentation on Enums:

enum UserResponse {
  No = 0,
  Yes = 1,
}
 
function respond(recipient: string, message: UserResponse): void {
  // ...
}

If the enum members are declared as const values, it results in a union enum, functioning as a union type.

Applying this concept to your provided example:

enum Enum {
  EnumValueA,
  EnumValueB
}

interface interfaceX { a: string, b: Enum }

const x: interfaceX = { a: 'mango', b: Enum.EnumValueA }

const y: Enum = Enum.EnumValueA

x.b = y

// With Enum as a union enum, flow analysis and logic checks mirror those of regular union types:
function f(arg1: Enum) {
  if (arg1 !== Enum.EnumValueA || arg1 !== Enum.EnumValueB) {
    // Error message regarding comparison being unintentional due to non-overlapping types.
  }
}

To allow assignment or passing of strings (e.g., 'EnumValueA') instead of specific enum references (Enum.EnumValueA), utilize the following approach:

// The type of arg1 will be: 'EnumValueA' | 'EnumValueB'
function f2(arg1: keyof typeof Enum) {
    // perform actions  
}

f2('EnumValueA')

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

Making if-else statements easier

Greetings! I have a JSON data that looks like this: { "details": { "data1": { "monthToDate":1000, "firstLastMonth":"December", "firstLa ...

How can I resolve the infinite loop issue caused by Angular Auth guard when using routing?

My current struggle lies within the authentication guard logic and routing setup. In my app-routing.module.ts file, I have defined 3 routes: const routes: Routes = [ { path: '', loadChildren: () => import('./browse/browse.mod ...

A unique Angular service that is private and initialized with a specific parameter

My Angular Service (myService) is injected into multiple components and services through their constructors. I want each usage of myService to have its own instance to ensure no data is shared among them. Additionally, I would like myService to be initia ...

What is the best way to change an existing boolean value in Prisma using MongoDB?

Exploring prisma with mongoDb for the first time and faced a challenge. I need to update a boolean value in a collection but struggling to find the right query to switch it between true and false... :( const updateUser = await prisma.user.update({ where: ...

typescript - specifying the default value for a new class instance

Is there a way to set default values for properties in TypeScript? For example, let's say we have the following class: class Person { name: string age: number constructor(name, age){ this.name = name this.age = age } } We want to ens ...

Tips for fetching individual item information from Firebase real-time database using Angular 9 and displaying it in an HTML format

product.component.ts import { AngularFireDatabase } from '@angular/fire/database'; import { ProductService } from './../product.service'; import { ActivatedRoute } from '@angular/router'; import { Component, OnInit} from &apo ...

Error: TypeScript compilation failed due to absence of tsc command in the system

Hello, I recently installed TypeScript and encountered an issue when trying to initialize tsc -v in the terminal. The error message I received was "bash: tsc: command not found." During the installation process, I used npm install -g typescript@latest whi ...

Converting Angular 5 select option values to strings is a must

I have set up a basic select connected to a variable like this: <select id="client" name="client" [(ngModel)]="order.clientId"> <option *ngFor="let client of clients" [value]="client.id"> {{ client.name }} </option> </ ...

Angular is throwing an error stating that it is unable to access the 'name' property of an undefined object

While working on my Angular application, I encountered the following error message: " Cannot read property 'name' of undefined" https://i.stack.imgur.com/O3vlh.png I've been searching through my code but am unable to pinpoint the issue. T ...

implement a solution in Ionic 4 Angular 6 that triggers a function only when all the observables in a loop have

In my code, I have a function named getDevices(). This function is responsible for fetching an array of devices. After getting this array, the code iterates through each device and calls another function called updateToServer(). The purpose of updateToServ ...

Is there a way to identify and retrieve both the initial and final elements in React?

Having an issue with logging in and need to retrieve the first and last element: Below is my array of objects: 0: pointAmountMax: 99999 pointAmountMin: 1075 rateCode: ['INAINOW'] roomPoolCode: "ZZAO" [[Prototype]]: Object 1: pointAmoun ...

Vue alert: Component resolution failed while attempting to create a global component

I am new to Vue Typescript and I have been encountering an issue while trying to create global components. I received a warning and the component did not load on the template. Here is how I attempted to create global components: App.vue import { createApp ...

Guide to adjusting the color of Fluent UI icon when hovering with mouse?

I've been implementing Fluent UI in my current project. When initializing my button, I use this straightforward JavaScript code: iconProps: { iconName: 'NewFolder', styles: { root: { color: 'orang ...

Tips for preventing circular dependencies in JavaScript/TypeScript

How can one effectively avoid circular dependencies? This issue has been encountered in JavaScript, but it can also arise in other programming languages. For instance, there is a module called translationService.ts where upon changing the locale, settings ...

Using TypeScript and Node.js with Express; I encountered an issue where it was not possible to set a class property of a controller using

I have a Node application using Express that incorporates TypeScript with Babel. Recently, I attempted to create a UserController which includes a private property called _user: User and initialize it within the class constructor. However, every time I ru ...

Generic parameter extending multiple types is utilized in a static field

What I have easily: I possess multiple enums that all extend a shared interface: interface CommonMethods { // some methods } enum E1 implements CommonMethods { O1, O2; // impls of interface methods } enum E2 implements CommonMethods { O ...

When attempting to declare a functional component in React utilizing styled-components in TypeScript, an error is encountered stating "No overload matches this call."

Playground https://codesandbox.io/s/typescript-type-checking-question-0b42t Sample Code type BadgeTypes = { success: string; secondary: string; alert: string; text: string; }; type Theme = { fonts?: object; borderRadius: string; primary?: o ...

Retrieve a single user using a query in the GraphQL platform

I've been struggling to create a GraphQL query in Express that retrieves only one user instead of all users every time. This is the query I'm using, incorporating TypeORM as my ORM: import { GraphQLList, GraphQLID } from 'graphql'; imp ...

The call stack size has been exceeded in Next.js, resulting in a RangeError

Currently attempting to deploy my project on vercel.com but encountering an error specifically with 3 pages that have no internal errors. An error occurred while prerendering the page "/applications". For more information, visit: https://nextjs.org/docs/me ...

Creating a layered image by drawing a shape over a photo in Ionic using canvas

While there are plenty of examples demonstrating how to draw on a canvas, my specific problem involves loading a photo into memory, adding a shape to exact coordinates over the photo, and then drawing/scaling the photo onto a canvas. I'm unsure of whe ...