TSeD amalgamated class Enumeration and Gathering

Currently using TSeD version 6.38.1 Presented here is my model:

import {Any, CollectionOf, Enum, Property} from "@tsed/schema";
export enum Status {
   status1,
   status2,
   ...
}

export class FilterParams {
  ... Additional fields

  @Any(Enum(Status), CollectionOf(Enum(Status)))
  status: Status[] | Status
}

I am facing challenges in annotating the status field within FilterParams. I aim for it to be either a single Status or an array of Status

Various annotations have been attempted with no success:

  1. @Enum(Status) status: Status[] | Status
    : Only accepts a single Status, rejecting arrays of Status
  2. @Enum(Status) status: Status: Similar to the above, only allowing single Status values
  3. @Enum(Status) status: Status[]: Strictly requires lists of Status and does not support arrays
  4. @Any(Enum(Status), CollectionOf(Enum(Status))) status: Status[] | Status
    : Results in AJV_VALIDATION_ERROR at runtime stating
    FilterParams.status.0 should be object.

How can this validation be achieved successfully in TSED?

Answer №1

Combining decorators in the way you've demonstrated is not supported and will not work.

To address this issue, it's best to utilize the function API for accurately defining the schema and leverage the OnDeserialize decorator to ensure that an array of Status is always maintained.

import {Any, CollectionOf, Enum, Property, string, array} from "@tsed/schema";
import {OnDeseriliaze} from "json-mapper";
export enum Status {
   status1,
   status2,
   ...
}
const StatusSchema = string().enum(Status)

export class FilterParams {
  ... Additional fields

  @AnyOf(StatusSchema, array().items(StatusSchema))
  @OnDeseriliaze(o => [].concat(o))
  status: Status[];
}

Until next time, Romain

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

Troubleshooting Next.js and Tailwind CSS Breakpoints: What's causing the

Having trouble with my custom breakpoints. For instance, I attempted the following: <div className="flex flex-row gap-5 mb-5 md:ml-15 sm:ml-15"> ... </div> The margin is not being applied on small and medium screens. Here are the th ...

Utilizing Angular 2 Component Input Binding with the Expression Mapping Function

Currently, I am working on a component that has an input of type array. class FooComponent { @Input() selectedItemIds:String[]; } I want to utilize a map expression in binding within the parent component. <app-foo-component [selectedItemIds]=&apo ...

Assigning object properties from a request to every item in an observable array of objects using RxJS

Despite my efforts to search various resources like mergeMap and switchMap, I am unable to solve the problem I'm facing as I am still new to RxJs. While I would like to provide more details about my attempts in this post, I fear it may complicate my q ...

Error: Visual Studio unable to locate Firebase node module

After running the command npm install firebase --save in the root of my project folder, a firebase folder was successfully added to my node_modules directory and the packages.json file was updated accordingly. In addition to using typescript, I have an ap ...

Ways to convert an asynchronous operation to synchronous in JavaScript

Currently in the process of developing an eslint plugin, I have come across a particular issue. My goal is to implement real-time changes to the configuration file by making an HTTP request to retrieve the JSON configuration. When attempting to execute co ...

What is the method to determine the length of a string with TypeScript?

Looking to derive the numerical length of a string: type Length = LengthOfString<"hello"> // ^? should equal 5 Feeling a bit lost on how to approach this. Any guidance on how to achieve this? (Currently diving into typescript's typ ...

Tips for interacting with the DOM in an Angular 4 application

I am trying to call the addItems method, but I keep getting an error: Uncaught TypeError: this.addItems is not a function Currently, I am using Angular 4 along with jQuery and the fullpage.js library. page-content.component.ts import { Component, OnI ...

What are the steps for creating and deploying a project that utilizes asp.net core on the server-side and Angular on the client-side

My latest project combines asp.net core 5 and angular 15 technologies for the backend and frontend, respectively. The asp.net core MVC portion of the project is contained in a dedicated folder named serverApi, while the angular part is generated in another ...

Issue encountered with the signature provided for a Safe API POST request

Watch this demonstration video of the issue at hand: I have created a signer using my Metamask Private Key and generated a signature from it as shown below: const signer = new ethers.Wallet(PRIVATE_KEY as string, provider) const safeInstance = new ethers. ...

Keeping the user logged in even after closing the app in an Ionic/Angular project: Best practices to retain user sessions

As a newcomer to angular/ionic, I have been given a project where the user needs to remain logged in even after closing the application unless they explicitly log out. Can anyone provide suggestions on how to modify the code below? login.page.ts import { ...

The Tumblr HTML code is not valid: There is a stray start tag for `html

Occasionally, I check my tumblog for validation in order to fix any errors. While most issues are easy to explain, there is one that has me stumped. What exactly does this mean? (please note: the outputted markup is out of my control) Error: Error: Stra ...

Looking for a specific phrase in the data entered by the user

I am dealing with data in ckeditor that looks like this: <p>test 1</p> <p>test 2</p> <p><img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICw ...

I am looking for a way to efficiently store and reuse rxjs lettable operators in multiple `.pipe()` calls without compromising TypeScript's type safety. Can anyone suggest a method to effectively "cache

(Just a heads up, this scenario is within an Angular 5 app, but not specific to Angular itself) I find myself using a set of operators repetitively in different parts of my code. To minimize redundancy, I grouped them in a base class: export class Compon ...

Testing the NestJS service with a real database comparison

I'm looking to test my Nest service using a real database, rather than just a mock object. While I understand that most unit tests should use mocks, there are times when testing against the actual database is more appropriate. After scouring through ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

Defining a TypeScript interface specifically tailored for an object containing arrow functions

I encountered an issue while trying to define an interface for the structure outlined below: interface JSONRecord { [propName: string]: any; } type ReturnType = (id: string|number, field: string, record: JSONRecord) => string export const formatDicti ...

Encountered an issue when utilizing the useRef hook in Next.js version 13

I am currently exploring nextjs13 and typescript. I encountered an issue when attempting to use the useRef hook. Below is the code snippet in question: import { useEffect, useRef } from "react" export const useDraw = () => { const canvas ...

Show all span elements in a map except for the last one

Within my ReactJS application, I have implemented a mapping function to iterate through an Object. In between each element generated from the mapping process, I am including a span containing a simple care symbol. The following code snippet demonstrates t ...

JavaScript code that displays values that are not equal

Here is a code snippet that checks whether two arrays of objects are equal or not. How can we enhance this code to log which answer is not matching? The structure of the arrays: arrayA represents user answered questions, while arrayB contains correct answ ...

IDE flags an error with TypeScript type declarations

Here is how my type definition looks: export type AuthType = boolean | { roles: string[]; assistant?: string[] } | (() => void); Now, I need to check the type of the auth variable and assign a value or execute a function in this line of code: req.all ...