Utilizing Typescript: Ensuring an array includes only specified values from an enum through strict enforcement

In my Angular application, I have an HTTP service that returns the allowed accesses for a specific user. The response structure is as shown below:-

{
    "accessId": 4209318492034,
    "folderPath": "data/sample_folder/",
    "permissions": [
        "READ",
        "WRITE"
    ]
}

The permissions field in the response is an array containing only two strings - "READ" (mandatory) and "WRITE" (optional). It may or may not include the WRITE permission.

To type this response using an interface and ensure that only certain strings are accepted in the permissions array, I defined an Enum like so:-

enum Permissions {
    READ = 'READ',
    WRITE = 'WRITE'
}

However, when I try to use this Enum in the UserAccess interface for the response, it doesn't seem to work as intended:-

export interface UserAccess {
    accessId: string;
    folderPath: string;
    permissions: Permissions[]
}

How can I enforce that the permissions array strictly includes values from the specified Permissions enum?

Answer №1

Avoid using enums, opt for types instead:

export type UserPermissions = 'READ'|'WRITE'

export interface AccessControl {
    accessId: string;
    folderPath: string;
    permissions: UserPermissions[]
}

Answer №2

Consider experimenting with the suggestions below:

export interface UserPermissions {
  accessLevels: (keyof typeof AccessLevels)[]
}

Keep in mind that TypeScript acts as a type checker during compilation and does not provide runtime enforcement.

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

Adding Custom CSS File to an iFrame in Angular

Currently, I am attempting to include a CSS file in a third-party iframe to modify its styling. My initial idea was to employ the following code snippet: ngOnInit() { ... this.myIframe.nativeElement.document.head.appendChild('style.css') } U ...

Evolving fashion trends

I'm looking to dynamically change the style of my HTML element based on screen size, similar to this example: <p [ngStyle]="{'color': isMobile() ? 'red' : 'blue'}">Lorem Ipsum</p> The code above triggers a m ...

Evaluating Angular/Typescript and its capabilities

I seem to be struggling with the concept of how eval functions in TypeScript/Angular. Can someone provide some guidance on how to make eval work in this scenario? Although the logic may not be perfect in this demo program, I just need help figuring out how ...

Accessing the state from a child functional component and then adding it to an array of objects in the parent component

I'm facing a challenge with a parent component that needs to manage the data of its child components stored in an array of objects. My goal is to add new child components and maintain their information within the parent's state as an array of obj ...

Eliminating the dynamic element in jQuery causes disruption to the ViewContainerRef container

In my Angular 2+ application, I am dynamically creating components using the following code snippet: @ViewChild("containerNode", { read: ViewContainerRef }) cardContainer; const factory = this.ComponentFactoryResolver.resolveComponentFactory(CardComponen ...

What does ngModel look like without the use of square brackets and parenthesis?

Can you explain the usage of ngModel without brackets and parentheses in Angular? <input name="name" ngModel> I am familiar with [ngModel] for one-way binding and [(ngModel)] for two-way binding, but I am unsure what it means when ngModel ...

unable to retrieve the value from the scope

I'm trying to implement the following code in HTML: <div ng-if="item.shareText"> <textarea></textarea> <div> <select ng-model="shareOptions"> <option value="PUBLIC" selected>public</option> ...

Trouble with scrolling on Kendo chart while using mobile device

I am facing an issue with multiple kendo charts on my website. These charts have panning and zooming enabled, but in the mobile view, they take up 100% of the width which causes touch events to not work properly for scrolling. I attempted to attach an even ...

Altering the appearance of an Angular component in real-time by applying various CSS style sheets

I'm currently working on implementing a dynamic style-sheet change for a single-page application using Angular. The concept is to offer users the ability to select from various themes through a dedicated menu. Although only two theme variants are show ...

Adding an additional element to an object - crossroads of combining types versus sequential examination

Here's a query for you: AppendToObject. When I first tackled this question, my initial instinct was to utilize type intersection like so: type AppendToObject<T, U extends PropertyKey, V> = T & {[P in U]: V} Unfortunately, this solution did ...

Error in Redirecting to Localhost

Recently, I developed an Angular App that interacts with the MS Graph API using MSAL. Initially, everything worked smoothly when running "ng serve" in Angular CLI. However, I encountered a problem when I packaged this Angular App with electron to deploy i ...

The latest version of https-proxy-agent is now 3.0.0, however, the npm audit is still indicating that

After the fix was provided for the NPM package https-proxy-agent on October 18, 2019, upgrading to the latest version still resulted in 6 high vulnerabilities being displayed in the audit warning. Even after running npm audit fix or npm audit fix --force ...

Navigating back to the top of a webpage within an Angular iframe on Safari desktop

One of my challenges involves an Angular 5 application which is embedded into an Iframe on various sites to create an application form. Whenever a user clicks 'Next' to move to the next section of the form, I require the page to scroll back to th ...

Struggling with integrating Axios with Vue3

Can someone assist me in figuring out what is going wrong with my Axios and Vue3 implementation? The code I have makes an external call to retrieve the host IP Address of the machine it's running on... <template> <div id="app"> ...

Tips on downloading a dynamically created XML file using ServiceStack and Angular

Although the code below is theoretically functional, it lacks proper error handling. The issue arises when the XML file starts downloading upon opening a new window with the URL generated by the service stack. In case of a server-side error, you are left o ...

Implement dynamic validation in Angular 4 based on specific conditions

I am looking to implement Angular 4 validation dynamically based on specific conditions within a Reactive form. Here is the scenario: There is a radio button with options: A: yes B: no If the user selects "yes", a textbox (formControlName="your_name") wil ...

Angular first renders a component before removing another one using ng-If

I have two components that are displayed one at a time using an ngif directive. <app-root> <first-Comp *ngIf="showFirst"></first-Comp> <second-Comp *ngIf="!showFirst"></second-Comp> </app-root> Here are some key ...

The gap between columns in Bootstrap grids

Currently, I am dynamically fetching "boxes" and adding them to the HTML document using ngFor. The number of boxes is unknown in advance. Here is the code I am currently using: <div *ngIf="items && items.length" class="row"&g ...

Develop your own personalized Angular schematics that produces a file that begins with an underscore

Having trouble with custom Angular schematics file naming. I'm trying to create a theme SCSS file that starts with an underscore followed by a double underscore as a delimiter. For instance, I want the file name to be _mouse-theme.scss, using the nam ...

Include token in src tag requests Angular version 8

In the process of developing a website, I have encountered a challenge. I am creating a platform where users can access another website I am currently working on after they log in. Once authorized, users receive a JWT token which is sent in the header with ...