Ensuring the Accuracy of String Literal Types using class-validator

Consider the following type definition:

export type BranchOperatorRole = 'none' | 'seller' | 'operator' | 'administrator';

Which Class-Validator decorator should I use to ensure that a property matches one of these values?

import { IsEmail, IsString, Contains } from "class-validator";

export type BranchOperatorRole = 'none' | 'seller' | 'operator' | 'administrator';

export class AddBranchOperatorRequest extends User {

    @IsEmail()
    email: string;

    @Contains(BranchOperatorRole )
    role: BranchOperatorRole;

}

Answer №1

const userRoles = ['none', 'seller', 'operator', 'administrator'] as const;
export type BranchOperatorRole = typeof userRoles[number];

export class AddBranchOperatorRequest extends User {

    @IsEmail()
    emailAddress: string;

    @IsIn(userRoles)
    role: BranchOperatorRole;

}

Answer №2

When it comes to validation, relying on Types at runtime is not feasible due to their disappearance. A common approach is to create an Enum and utilize the IsEnum decorator for validation. Check out this example for reference.

For your specific scenario, consider implementing something like the following:

export enum BranchOperatorRoleEnum = {
  none=1,
  seller=2,
  // other
}

class AddBranchOperatorRequest {
    @IsEnum(BranchOperatorRoleEnum)
    role: BranchOperatorRole;
}

If preferred, you can also use an array instead of an enum:

export type BranchOperatorRole = 'none' | 'seller' | 'operator' | 'administrator';

export const BranchOperatorRoles: BranchOperatorRole[] = [
  'none',
  'seller',
  // other
]

class AddBranchOperatorRequest {
    @IsEnum(BranchOperatorRoles)
    role: BranchOperatorRole;
}

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

Implementing a variable for an array in Angular 4: A step-by-step guide

I need help determining the correct value for skill.team[variable here].name in Angular, where all team names are retrieved from the skill. Below is the code snippet: HTML <select [(ngModel)]="skill.teams[1].name" name="teamName" id="teamName" class= ...

Getting object arguments from an npm script in a NodeJS and TypeScript environment can be achieved by following these steps

I'm trying to pass an object through an NPM script, like this: "update-user-roles": "ts-node user-roles.ts {PAID_USER: true, VIP: true}" My function is able to pick up the object, but it seems to be adding extra commas which is ...

The JSX component cannot be utilized as `ToastContainer`

Check out this Code: import axios from "axios"; import React, { useState, useEffect } from "react"; import { ToastContainer, toast } from "react-toastify"; import loaderIcon from "../../assets/images/loader.gif"; imp ...

What is the best way to verify the type of an object received from request.body in Typescript

Is it possible to check the object type from the request body and then execute the appropriate function based on this type? I have attempted to do so in the following manner: export interface SomeBodyType { id: string, name: string, [etc....] } ...

I am experiencing an issue with mydaterangepicker and primeng where it is not displaying properly in the table header. Can anyone assist me with this

I am attempting to integrate mydaterangepicker () with primeng turbotable (since primeng calendar does not meet the requirements), but I am having trouble with its display. Could you please assist me with some CSS code or suggest an alternative solution? ...

Show the textbox automatically when the checkbox is selected, otherwise keep the textbox hidden

Is it possible to display a textbox in javascript when a checkbox is already checked onLoad? And then hide the textbox if the checkbox is not checked onLoad? ...

Having issues with Vue 3 Typescript integration in template section

This particular project has been developed using the create-vue tool and comes with built-in support for Typescript. Key versions include Vue: 3.3.4, Typescript: 5.0.4 Here is a snippet of the code to provide context: // ComponentA.vue <script setup l ...

The interfaces being used in the Redux store reducers are not properly implemented

My Redux store has been set up with 2 distinct "Slice" components. The first one is the appSlice: appSlice.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import type { RootState } from "./store"; export interface CounterState { value ...

The Subscribe function in Angular's Auth Guard allows for dynamic authorization

Is there a way to check if a user has access by making an API call within an authentication guard in Angular? I'm not sure how to handle the asynchronous nature of the call and return a value based on its result. The goal is to retrieve the user ID, ...

Version 4.0 of d3 introduces an import statement that provides a __moduleExports wrapper

Having difficulty with an import statement in my D3 4.0 and Ionic2/Angular2 project. I believe the import statement is correct, as everything compiles successfully. import * as d3Request from 'd3-request'; export class HomePage { construc ...

How can we optimize component loading in react-virtualized using asynchronous methods?

In my component, I have implemented a react-virtualized masonry grid like this: const MasonrySubmissionRender = (media: InputProps) => { function cellRenderer({ index, key, parent, style }: MasonryCellProps) { //const size = (media.submiss ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

typescript function intersection types

Encountering challenges with TypeScript, I came across the following simple example: type g = 1 & 2 // never type h = ((x: 1) => 0) & ((x: 2) => 0) // why h not never type i = ((x: 1 & 2) => 0)// why x not never The puzzling part is w ...

When utilizing the package, an error occurs stating that Chart__default.default is not a constructor in chart.js

I have been working on a project that involves creating a package with a react chart component using chart.js. Everything runs smoothly when I debug the package in storybook. However, I encountered an error when bundling the package with rollup, referenc ...

angular2 - Having trouble retrieving data from subject

Why am I unable to successfully initialize and retrieve data from a service using a subject in Angular? HomeComponentComponent.TS export class HomeComponentComponent implements OnInit { public homeSub; constructor( private subService: SubjectServ ...

Angular rxjs: Wait for another Observable to emit before subscribing

My setup involves having 2 subscriptions - one is related to my ActivatedRoute, and the other is from ngrx Store. ngOnInit() { this.menuItems$ = this.store.select('menuItems'); this.menuItems$.subscribe(data => { this.menuItem ...

Asynchronous task within an if statement

After pressing a button, it triggers the check function, which then executes the isReady() function to perform operations and determine its truth value. During the evaluation process, the isReady() method may actually return false, yet display "Success" i ...

The expanded interfaces of Typescript's indexable types (TS2322)

Currently, I am in the process of learning typescript by reimagining a flowtype prototype that I previously worked on. However, I have hit a roadblock with a particular issue. error TS2322: Type '(state: State, action: NumberAppendAction) => State ...

Exploring Angular 8 HTTP Observables within the ngOnInit Lifecycle Hook

Currently, I am still a beginner in Angular and learning Angular 8. I am in the process of creating a simple API communication service to retrieve the necessary data for display. Within my main component, there is a sub-component that also needs to fetch ...

Sharing Properties Across Angular Components using TypeScript

Seeking a solution for storing properties needed in multiple components using a config file. For example: number-one-component.ts export class NumberOneComponent { view: any[]; xAxis: number; yAxis: number; label: string; labelPositio ...