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

Issue with Angular 2 Observable testing: Trying to use setInterval in an async zone test is not allowed

I am currently in the process of testing a component that relies on a service for making asynchronous HTTP calls. The service returns an Observable, which is then subscribed to by the component. Snippet from the service code: getRecentMachineTemperatures ...

Tips for saving a variable in Angular that is being received through a subscription as JSON:

Below is an example of the json I have: [{"id":"1","date":"2020-02-21","status":"present","studentid":"1"},{"id":"2","date":"2020-02-24","status":"present","studentid":"1"}] I am struggling to store the date in a variable using Angular when it is being s ...

Using the `import.meta` meta-property is restricted to the `es2020`, `esnext`, or `system` options in snowpack+testing-library and will result in an error

I've been encountering issues while setting up Jest and React Testing Library for the snowpack project. The error message I'm receiving is "The 'import.meta' meta-property is only allowed when the '--module' option is 'es ...

Angular 8 throws a TS2339 error, yet the code is functioning perfectly and delivering the desired output

Upon compiling my code, I encountered the following error: ERROR in src/app/home/home.component.ts:13:37 - error TS2339: Property 'name' does not exist on type 'string | Type'. Property 'name' does not exist on type &ap ...

Looking for a way to toggle the visibility of a dropdown list when clicking on an input in Angular7?

My Angular7 application features a dropdown menu that automatically closes when an item is selected. Additionally, I have implemented functionality to toggle the dropdown open and closed by clicking on an input field. You can view a live example of this be ...

Create a union type by utilizing indices of an array type

For instance: type BasicTheme = { name: 'basic'; colors: [string, string]; }; type AdvancedTheme = { name: 'advanced'; colors: [string, string, string, string]; }; type MainColor = ???; // 'main-1' | 'main-2&apo ...

NGRX effect in Nativescript Angular loses state when the app is suspended on iOS

While using NGRX with Nativescript Angular to manage state and fetch data from the server, I've encountered an issue when suspending the app on IOS. Whenever the app is in the middle of fetching data from the server and gets suspended, the entire proc ...

What is the best way to display a JSON array in Angular 4?

Check out this JSON structure: -------------------------------------------------- "id": 2, "user": { "id": 1, "name": "User", "surname": "User", "email": "<a href="/cdn-cgi/l/email-protection" ...

Issues arise when trying to implement Angular SCSS with ngx-datatable

I am encountering an issue with my SCSS. It seems that the CSS command from the SCSS file below is not being utilized. This particular SCSS file is generated with the component. Interestingly, when I place the code in the styles.scss file included in the ...

Troubleshooting: Resolving JSX props issue in Vue template

Ever since integrating the FullCalendar library into my Vue project, I've been encountering an error every time I try to use my custom component in a Vue template. My setup includes Vue 3, Vite, VSCode, eslint, and prettier. This issue seems to be m ...

After closing and reopening the app, I noticed that the ionic slider images fail to display until I navigate to the next page

//// How can I retrieve the data for (let i = 0; i < res.length; i++) { let item: any = {}; item.slide = res.item(i).slide; items.push(item); } this.productsService.setSlideList = items; setTimeout(() => { this.sliderImage = items; consol ...

Creating divs dynamically in a loop and displaying them upon clicking a button in Angular

I am trying to dynamically create divs in a loop and show the selected div when I press a specific button. In theory, this is how I envision it... <div>div1</div><button (click)="showDiv(divID)">showDIV</button> To hide a ...

Guide to configure Validator to reject the selection of the first index option in Angular 2

When using a select option, it should be set up like: <div class="form-group row" [ngClass]="{'has-error': (!form.controls['blockFirstIndex'].valid && form.controls['blockFirstIndex'].touched), 'has-success&ap ...

`Browser Extension Compatibility``

I am currently working on developing a TypeScript extension that is compatible with all major browsers. I have come across the package https://www.npmjs.com/package/web-ext-types which I have integrated into my package.json file. While coding in TypeScrip ...

Aggregate the data chunks in the antd table into groups

I've been struggling to find a solution for this specific issue. My goal is to group the data in my table based on a particular field, but I need it to be styled as depicted in the image linked below. https://i.stack.imgur.com/OsR7J.png After looking ...

How can I display options in a react autocomplete feature?

Using the autocomplete component from @material-ui/lab/autocomplete, I am trying to retrieve the title_display result in the options field. These results are being fetched from an API using axios. You can view my code here--> https://codesandbox.io/s/r ...

The contenteditable DIV function is experiencing issues with Angular's two-way binding feature in the Firefox browser

After making my div contenteditable and triggering ngx-popover on keyup to display search results based on searchText, I am in need of two-way binding along with content editability. However, I prefer using a div instead of an input element: <span> ...

The "isActive" value does not share any properties with the type 'Properties<string | number, string & {}>'. This issue was encountered while using React with TypeScript

I'm attempting to include the isActive parameter inside NavLink of react-router-dom version 5, but I'm encountering two errors. The type '({ isActive }: { isActive: any; }) => { color: string; background: string; }' does not have an ...

Integrating TypeScript into an established create-react-app project

Struggling to integrate TypeScript into an existing create-react-app? I've always added it at the beginning of a project using create-react-app my-app --scripts-version=react-scripts-ts, but that's not working this time. The only "solution" I co ...

Leveraging the power of Angular4 to dynamically iterate through SVG elements with the

Currently, I am utilizing SVG for font-icons and it is performing flawlessly. However, I have encountered a significant issue while employing *ngFor in my code: <ion-col col-3 *ngFor="let land of landscape_amenities> <span class="icon-{{land. ...