Passing `any` or `any[]` as a function parameter in Types

Recently, I've been working on enhancing my validation middleware to accommodate for both classes (any) and arrays (any[]) as input. Initially, this middleware was set up to take in a single class type as an input parameter. However, I managed to modify it successfully to accept array types as well. The hiccup came when I attempted to allow for both class and array types simultaneously.

import { plainToClass } from 'class-transformer';
import { validate, ValidationError } from 'class-validator';

const validateType = (
  type: any | any[],
  value: string,
): void => {
    validate(plainToClass(type, value), { }).then((errors: ValidationError[]) => {
        if (errors.length > 0) {
            console.log(`Errors found`);
        } else {
            console.log(`Success`);
        }
    });

When passing a class as input, the function compiles successfully. However, it fails when an array is provided as input;

class CreateObjectDto {
  public a: string;
  public b: string;
}

const inputString = "{a: \"something\", b: \"else\"}"
const inputArray = "[{a: \"something\", b: \"else\&\quot;}], [{a: \"another\", b: \"more\"}]"

validateType(CreateObjectDto, inputString); // pass
validateType(CreateObjectDto, inputArray); // fail

By modifying the function signature to only accept arrays (type: any[]), the function runs without any issues. However, I'm struggling to find a way to specify the input type as either a single class or an array of classes.

I am open to suggestions on how to declare CreateObjectDto[] as an input parameter for the function. Alternatively, I'd appreciate any insights on adjusting the function signature to effectively distinguish between a single class and an array of classes within the input string.

Thank you!

Answer №1

When you require a function signature that accepts either any or any[], you must create an implementation that can differentiate between the types and handle the argument accordingly. Here is an example of how to achieve this:

function checkDataType(
  dataType: any | any[],
  dataValue: string,
): void {
  if (dataType instanceof Array) {
    dataType // any[]
  } else {
    dataType // any
  }
}

Try it out in TypeScript playground

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

Clicking on an iFrame button will open the results in a new tab

Within one of my tabs, there is an iFrame tag that displays results from an insurance agency when the 'Compare now' button is clicked. <iframe src="https://www.compulife.net/website/1295/quoter.html" width="750 pixels" id="test" name="test" h ...

jest - SyntaxError: Unexpected token 'export'

I am currently utilizing vue.js and attempting to incorporate async/await in jest (with vue utils test). it('async/await test', async () => { await wrapper.setData({ foo: 'bar', }); // ... }); Although I can us ...

Include on-hover functionality when my page is viewed on a smartphone

When I access your webpage from a computer and hover over the menu, a language selection menu pops up. I would like to achieve the same functionality when using a smartphone. I have attempted to implement this using Hammer.js, but so far it has not been ...

Unable to make custom font work in TailwindCSS and ReactJS project

I have incorporated a custom font into my projects using React, TypeScript, TailWind, and NextJS. The font file is stored in the /fonts directory with the name Glimer-Regular.ttf. To implement the font, I added the following code snippet to my global.css ...

Tips for transferring a reference to a variable, rather than its value, to a method in VueJS

Within my template, there is this code snippet: <input @input="myMethod(myVariableName)" /> Following that, I have the myMethod function: myMethod(variablePassed) { console.log(variablePassed) } Upon execution, I receive the value of th ...

Stop the iframe video when the modal is closed

I'm currently developing a website that incorporates the code showcased in this tutorial to launch a modal window featuring an iframe for playing YouTube or Vimeo videos. The issue arises when, as mentioned in the comments on the tutorial page, there ...

Due to high activity on the main thread, a delay of xxx ms occurred in processing the 'wheel' input event

While using Chrome version: Version 55.0.2883.75 beta (64-bit), along with material-ui (https://github.com/callemall/material-ui) version 0.16.5, and react+react-dom version 15.4.1, an interesting warning message popped up as I scrolled down the page with ...

What is causing my divs to behave as if I set a margin-top/margin-bottom of one and a half centimeters?

I'm currently developing an AngularJS application and I've encountered some issues with unnecessary whitespace. <div class='user' ng-repeat='session in sessions'> <div class='text' ng-bind='monolog ...

TypeScript does not evaluate the boolean left operand when using the && operator

While working with TypeScript, I encountered a scenario similar to the code snippet below: const getString = (string: string) => string // No errors getString("foo"); // Argument of type 'boolean' is not assignable to parameter of ...

Custom directives are unable to interact with inbuilt directives

var app = angular.module("myDiscuss", []); app.controller("TabController", function() { this.tab = 0; this.subTab = 0; this.like = 0; this.selectLike = function(setTab) { this.like= setTab; }; this.selectTab = function(setTab) { this. ...

AngularJS is struggling to retrieve information from an Asp.net webapi 4 endpoint

I'm currently in the process of developing an application using Asp.net Web API and AngularJS. While attempting to retrieve data from the API, I encountered a null error. Asp.net Web API Code [RoutePrefix("api/user")] public class UserController : ...

Problematic Angular 6 Lazy Loading Situation

Below is the code snippet I am using for lazy loading: const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'manager', lo ...

What is the minimum number of lines that can be used for javascript code?

Currently, I am in the process of developing a custom JavaScript minifier. One question that has come up is whether it is necessary to insert line breaks after a certain number of characters on a single line, or if it even makes a difference at all? For i ...

"Error: The functionality of finding places on Google Maps is not

I've encountered an issue while trying to integrate Google Maps into my Node application. The map is loading correctly and I'm able to retrieve my location. However, I am facing a problem with implementing the Google Places API code to allow user ...

Incorporating a lasting element into the _app.js file of Next.js

I am currently experimenting with my first Nextjs app and encountering difficulties when trying to incorporate a persistent sidebar. While looking for solutions, I came across Adam Wathan's article on persistent layouts in Nextjs. However, it appears ...

No search results found for Mongoose text search query

Despite using Mongoose 5.7.8 for my app, the text search feature is not yielding any results. Below is a schema/model example: import mongoose, { Document, Schema } from 'mongoose'; import { Moment } from 'moment'; import { IUser } fr ...

Validate AngularJS forms by displaying error messages based on the server's response

Within my form, I am checking for the existence of an email address. If the email already exists, I display an error message from the JSON response when the user clicks the submit button. When the email already exists, I receive a 409 error. I am looking ...

Converting a string to Time format using JavaScript

I am working with a time format of 2h 34m 22s which I need to parse as 02:34:22. Currently, I am achieving this using the following code: const splitterArray = '2h 34m 22s'.split(' '); let h = '00', m = '00', s = &a ...

Im testing the creation of a global style using styled-components

Is there a way to create snapshot tests for styled-components with createGlobalStyle? The testing environment includes jest v22.4.4, styled-components v4.1.2, react v16.7, jest-styled-components v5.0.1, and react-test-renderer v16.6.3 Currently, the outp ...

In React, the Textarea component that displays the character count only updates its value after a page reload

Contained within this element is the following component: import React, { useEffect, useState } from 'react'; import { TextareaTestIds } from '../utils/test-ids'; export interface TexareaProps extends React.TextareaHTMLAttributes<H ...