Validate that the input is an array

Looking for a way to determine if a function parameter is an array or not, and then process it accordingly. If the parameter is not an array, convert it into an array before performing the desired function.

For example:

interface employee {
    first: string,
    last: string
}

function updateEmployees (emp: employee | employee[]) {
    let employees = [];
    if (emp instanceof Array) employees = [emp];
    else employees = emp;
    employees.forEach(function(e){
        return 'something'
    })
}

While this logic seems correct, it's raising a warning stating

Type 'employee' is not assignable to type 'any[]'. Property 'length' is missing in type 'employee'.

Answer №1

Check out the revised version of your code:

function updateStaff (staff: employee | employee[]) {
    let employees: employee[] = [];
    if (Array.isArray(staff)) employees = staff;
    else employees = [staff];
    employees.forEach(function(e){
        return 'something'
    })
}

Alternatively, you can make it more concise:

function updateStaff(staff: employee | employee[]) {
    (Array.isArray(staff) ? staff : [staff]).forEach(function(e){
        return 'something'
    })
}

Answer №2

Here is a function in Typescript that ensures an array is returned safely. It checks for null or undefined items and returns an empty array if found.

function safeArray<T>(value: T | T[]): T[] {
  if (Array.isArray(value)) {
    return value
  } else if (value === undefined || value === null) {
    return []
  } else {
    return [value]
  }
}

If you want to include null or undefined items:

function safeArray<T>(value: T | T[]): T[] {
  if (Array.isArray(value)) {
    return value
  } 
  else {
    return [value]
  }
}

Usage example:

function updateEmployees(emp: employee | employee[]) {
    safeArray(emp).forEach(function(e){
        return 'something'
    })
}

The additional check prevents runtime errors when encountering null or undefined elements, ensuring the loop iterates only over 'employees'.

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

Interactive 3D model movable within designated area | R3F

I am currently facing a challenge in limiting the drag area of my 3D models to the floor within my FinalRoom.glb model. After converting it to tsx using gltfjsx, I obtained the following code: import * as THREE from "three"; import React, { useRe ...

Discovering if an agent is a mobile device in Next.js

I am currently working with nextjs version 10.1.3. Below is the function I am using: import React, {useEffect, useState} from "react"; const useCheckMobileScreen = () => { if (typeof window !== "undefined"){ const [widt ...

How can I suggest the return type of a function that is out of my control?

When I attempt to parse a JSON-formatted string, a linter error is triggered: let mqttMessage = JSON.parse(message.toString()) // ESLint: Unsafe assignment of an `any` value. (@typescript-eslint/no-unsafe-assignment) Given that I am in control of the con ...

Leveraging the combination of <Form>, jQuery, Sequelize, and SQL for authentication and navigation tasks

My objective is to extract the values from the IDs #username-l and #pwd-l in an HTML form upon the user clicking the submit button. I aim to compare these values with those stored in a SQL database, and if they match exactly, redirect the user to a specifi ...

javascript ondrag while self-pressing

Within this div, I have a series of p elements. My goal is to drag the selected element into the input field. Here's an example: var input = document.getElementById("test"); input.addEventListener('drop', function (event) { event.pr ...

Discover the power of catching Custom DOM Events in Angular

When working with an Angular library, I encountered a situation where a component within the library dispatches CustomEvents using code like the following: const domEvent = new CustomEvent('unselect', { bubbles: true }); this.elementRef.nati ...

Using jQuery to target nested HTML elements is a great way to efficiently manipulate

Within the code below, I have a complex HTML structure that is simplified: <div id="firstdiv" class="container"> <ul> <li id="4"> <a title="ID:4">Tree</a> <ul> <li id="005"> ...

Create random animations with the click of a button using Vue.js

I have three different lottie player json animation files - congratulations1.json, congratulations2.json and congratulations3.json. Each animation file is configured as follows: congratulations1: <lottie-player v-if="showPlayer1" ...

Unveil as you scroll - ScrollMagic

I am working on a skill chart that dynamically fills when the document loads. I am exploring the possibility of using ScrollMagic to animate the chart filling as the user scrolls down. After trying various combinations of classes and pseudo-classes in the ...

Update state within React components without impacting any other state variables

Imagine I have an object structured like this: person : { name : "Test", surname : "Test", age : 40, salary : 5000 currency : "dollar", currency_sign : "$", . . . } I am looking to achieve the following I will make ...

Creating a server that is exclusive to the application in Node.js/npm or altering the response body of outgoing requests

As I work on developing a node app, the need for a server that can be used internally by the app has become apparent. In my attempts to create a server without listening to a port, I have hit a roadblock where further actions seem impossible: let http = ...

The HTML embed element is utilized to display multimedia content within a webpage, encompassing

Currently, I am working on a static website for my Computer Networks course. Students need to be able to download homework files in PDF format from the website. I have used embed tags to display the files online, but I'm facing an issue where the embe ...

Gulp does not generate any new folders

Currently, my workspace is located in a directory named "Super gulp" with other directories that contain my files. The issue I'm facing is related to converting my .pug files into HTML files and placing them in the "goal" directory. However, when I tr ...

Is it possible for npm to assist in determining the appropriate version of Primeng that is compatible with Angular 16 dependencies

While trying to add primeng to my project, I ran into an error message: npm i primeng npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

The issue with Ajax file upload is that it only processes the first file in the filelist array for

I am struggling with an issue while using jquery and materialize for asynchronous file upload and form submit. The code seems to work fine when I use get(0).files[0], but it only returns the first file at index [0]. However, when I attempt to loop through ...

Error in React-Native: Unable to locate main project file during the build process

Just integrated cocoapods into a React Native project. After a successful build, RN is throwing this error... https://i.stack.imgur.com/czn2W.png No errors in Xcode during the build process, but Xcode is displaying these warnings https://i.stack.imgur.c ...

AngularJS enables box to smoothly slide up and down when hovered over

I am attempting to create a div that will overlay an image on hover with a slide up and slide down effect. Can anyone provide guidance on how to achieve this without relying on jQuery? I would prefer to utilize only AngularJS in my application. Here is a ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

Index.js is dynamically importing a .tsx file post-build, with a specific focus on Windows

While working on my project, I decided to customize a module by cloning it and making some changes. After installing the dependencies and building it, I encountered an error when trying to run it. The error message stated: Error: Unable to resolve module & ...

Learn how to showcase video information in a vue.js template

I am having difficulty displaying a saved media (video) file on another page after collecting it using the ckeditor5 media option. The data is stored along with HTML tags generated by ckeditor, so I'm using v-html to display other content like <p&g ...