What is the method for utilizing enum values as options for a variable's available values?

I'm curious about using enum values in TypeScript to restrict the possible values for a variable. For example, I have an enum named FormType with Create and Update options. Is there a way to ensure that only these enum values are used?

enum FormType {
   Create = 1,
   Update = 2
}

// Is it possible to do something like this?
const a: FormType = FormType.Create // Preventing other values like 3 from being used

// Maybe something like this instead?
const a: FormType.Create | FormType.Update = FormType.Create

Answer №1

You're currently on the right track by defining the enum and using it as a type. However, keep in mind that this approach is effective only during the programming stage.

When the code is transpiled, TypeScript will convert it into a JavaScript Object, and there won't be any built-in "checks" at runtime. If you require validation, you'll have to manually verify if the type is present in the enum - like so:

if(!Object.values(MyEnum).includes(value)) throw new Error('Invalid type for enum');

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

Navigating in express

Here is the structure I am working with: server.ts routes/ index.ts homeRoute.ts In server.ts: let app = Express(); app.use(router); In routes/index.ts: const routes = Router(); export default function router() { routes.use('/home' ...

Executing a function in the view/template with Angular 2+

Whenever a function is called in the view of an Angular component, it seems to be executed repeatedly. A typical example of this scenario can be seen below: nightclub.component.ts import { Component } from '@angular/core'; @Component({ selec ...

Unable to upload file in angular2 due to empty Body (FormData)

Attempting to upload a photo with Angular2 to my REST Service (Loopback). The Loopback service has been successfully tested using Postman and is able to accept files with the x-www-form-urlencoded header. Below is a simplified version of the service metho ...

The NgModel within the parent component is expected to mirror the state of the child component

My Angular 10 project includes a library with a wrapper component around a primeng-component. The primeng-component utilizes ngModel. I am trying to set the ngModel in the parent-component accessing the wrapper-component, and I want any changes made to the ...

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 ...

Unable to install @angular/fire due to compatibility conflicts

Upon running npm outdated, I attempted to update some outdated packages without fully understanding the implications, thinking it was necessary for updating them. However, what I truly need is to install Angular Fire, as indicated by this error message: ...

Incorporate an HTML span element with an onclick function bound in Angular framework

Is there a way to incorporate different icons by adding a span based on a flag, with an onclick event that triggers an internal function defined in the component ts? testfunc(){ console.log("it works") } flagToIcon(flag: boolean) { switch ( ...

The TypeScript Promise error codes TS2304 and TS2529 are causing confusion among

I came across the code below: function asyncTask(): Promise<string> { return new Promise<string>(resolve => resolve); } This code resulted in the following error: TS2304: cannot find name 'Promise' To address this issue, ...

A specialized solution designed to avoid loops in references

Is there a method to create a general solution that can prevent circular variables in JavaScript? This solution should be effective for any level of depth or type of circular reference, not limited to the variable itself... So far I've come up with t ...

What is the hierarchy of importance for routes in Angular - parent versus child levels?

Let's say I define a top-level route with the path '/some/childr': [{ path: '/some/childr'}] Then, I create another top-level route /some with a child route /childr: [{ path: '/some', children: ['/childr']}] ...

Can the NgModule objects be imported from an external file?

One of my goals is to streamline the organization of my app by putting everything into logical files. I frequently do this in C#. Is there a way to extract declarations into a separate file and then assign the value to the declarations variable on NgModule ...

Is there a way to retrieve just one specific field from a Firestore query instead of fetching all fields?

I am experiencing an issue where I can successfully output all fields in the console, but I only want to display one specific field. In this case, I am trying to retrieve the ID field but I am encountering difficulties. Below are screenshots illustrating m ...

Is there a way to define the length of children when performing props type checking?

I need my component to only allow for three children that are considered as type React.ReactChild. However, I'm uncertain if ReactChild is the most suitable type to validate. Essentially, these children should be three distinct sections. function Top ...

Navigating with finesse in Angular2

My goal is to generate dynamic routes using the index names from my elastic index. I successfully implemented dynamic routing by manually adding some names, but encountered an issue when trying to insert routes with my elastic index names. In my app.routi ...

An issue arises in Typescript when attempting to pass an extra prop through the server action function in the useForm

I am struggling with integrating Next.js server actions with useFormState (to display input errors on the client side) and Typescript. As per their official documentation here, they recommend adding a new prop to the server action function like this: expo ...

Show values in an angular template using an array

I want to showcase values of an array using *ngFor const blockData = [ {text: sampleText1, array: [val1]}, {text: sampleText2, array: [val2, dat2]}, {text: sampleText3, array: [val3, dat3]} ] <div *ngFor="let data of blockData"> ...

What is the best way to ensure that the first tab is always pre-selected among dynamic tabs?

I'm currently working on an angular 4 project and I need to implement a feature where there are three checkboxes. When the first checkbox is selected, a new tab should be dynamically created. So, if all three checkboxes are selected, there will be thr ...

Route Handler 13 is encountering difficulties in retrieving data from the body in the (app/api/auth) endpoint

Whenever I attempt to retrieve the body from the new export async function POST( req: Request), it seems to come through as a stream instead of the expected content type. The route handler can be found in api/auth/signup See folder layout image export asyn ...

"Stylish form field design with outlined borders that displays a subtle hover

I am attempting to modify the background color of a mat-form-field outlined when hovering with the mouse. .mat-form-field.mat-form-field-appearance-outline.mat-form-field-outline-thick { // HOVER EFFECT background-color: $dark-blue-200; } The above ...

What is the process for incorporating a manually created Angular package into a project as a node modules package?

Looking for help on integrating a custom-built package into an Angular project instead of the default one installed via npm. I attempted to replace the original package in node_modules with my custom build, but encountered issues. The specific package I& ...