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

Querying a subarray in MongoDB

Here is a document I have: { "_id" : "someId", "name" : "myTeam", "team" : [ { "entity" : "size", "value" : 14 }, { "entity" : "returns", ...

What is the best way to show and hide the information in a FAQ section when each one is clicked?

const faqItems = document.getElementsByClassName("faq-question"); const faqContents = document.getElementsByClassName("faq-content"); for (item of faqItems) { console.log(item); item.addEventListene ...

Padding in C arrays refers to adding extra bytes to

In my code, I have various data arrays defined with only the length specified in the array initializer. int x[] = {1, 2, 3, 4}; int y[] = {1, 2, 3, 4, 5}; To ensure cache line coherence, I need to pad them to a cache line size of 32. The code below can be ...

Vue.js with TypeScript: The property 'xxx' is not found on the type 'never'

I have a computed method that I am trying to execute: get dronesFiltered(){ const filtered = this.drones.filter((drone) => { return drone.id.toString().indexOf(this.filterId) > -1 && drone.name.toLowerCase().toString().in ...

AngularJS fails to recognize Iframe element during REST request

I'm having trouble with my webpage only reading the Iframe tag. It's sending the content correctly according to Postman. Postman is giving me this content: "Conteudo": "<p>Test iframe:</p>\n\n<p><iframe framebord ...

How to retrieve an object's property within a component

Currently, my goal is to retrieve the email property from the user object {"name":"test", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582c3d2b2c182c3d2b2c7620">[email protected]</a>"} I want to achie ...

What is the process for incorporating items from Slick Grid into a Multi Select TextBox?

Exploring the world of Slick Grid for the first time. Here is where I define my variables in JavaScript. var grid; var printPlugin; var dataView; var data = []; var selectdItems = []; var columns = [ { id: "Id", name: "Id", field: "Id", sortable: t ...

The tablet is having trouble playing the mp3 audio file

When clicking on an mp3 audio file, I want the previous file to continue playing along with the new one. While this works perfectly on browsers with Windows machines, there seems to be an issue when using a tablet. The second mp3 stops playing when I clic ...

Converting an Array into JSON Format Using Java

I need to tackle the task of converting an ArrayList containing users from Java to JSON format. While I have successfully figured out how to convert a single user, I am struggling with the syntax required for handling arrays. The following code snippet is ...

Executing a Jquery click event after a delay with setTimeout

I am working with an <a> element that, when clicked, triggers a handler like this: function onCummReportClick(e) { if ($(e.currentTarget).attr('href').indexOf('csv') !== -1) { { return true; } //Here s ...

Is there a maximum number of window.open() calls that can be made in JavaScript?

Can the use of window.open("URL"); in JavaScript be limited? Upon attempting to open three windows using window.open("URL"), the third window did not open separately. Instead, it refreshed the contents of the first window and displayed the contents of ...

Steps to enable ng-model input HTML in AngularJS

I am working on an HTML code snippet that includes a form input for audio link. However, when I try to enter a URL in the input field and submit the form, I encounter the following errors: <div class="inner-content-linkaudio"> <label for="linka ...

New from Firefox 89: The afterprint event!

Having an issue with this fragment of code: const afterPrint = () => { this.location.back(); window.removeEventListener('afterprint', afterPrint); }; window.addEventListener('afterprint', afterPrint); window.print(); I&apos ...

Leveraging the sibling combinator for altering the class of a sibling SVG element with the assistance of Material

I have created an SVG picture that I am trying to animate. Behind the elements I want to animate on mouse hover, I have added transparent rectangles. The hover effect works well on these elements as the cursor changes to pointer. However, when I attempt t ...

Is there a way to determine when an HTML video has finished playing?

I'm working on a webpage that features multiple videos. I want to capture a specific value from an input field and display it once a video finishes playing. Below is my current setup: HTML <input type='text' name='profileUsernam ...

JavaScript code to retrieve and store data from API endpoints

I am working with a Web API endpoint that provides the location of a URL (). When a button is clicked, this API is called and a URL is returned. The file format could be PDF, Excel, or Word. I am looking for a way to download the file and save it to disk ...

Displaying data in JSON format retrieved from a MySQL database

Greetings everyone! I am currently working on a website built with CodeIgniter. In one of my functions, I need to fetch data from MySQL and display the result in JavaScript as part of an Ajax call. Here is my PHP function for retrieving data: public func ...

Leveraging typegoose in a multitenant environment within the nestjs framework

I am looking to implement multitenancy functionality where each tenant will have its own database. Can Typegoose dynamically create connections for this purpose? ...

Explaining the process of defining a function and addressing the situation of inserting "variable parameters/arguments" in case the first parameter/argument is deemed incorrect

I came across an interesting article called Callback Hell, which discusses the common practice of handling errors in callbacks. The article mentions that in Node.js, it is typical to designate the first argument of a callback function for error handling pu ...

"Is it possible to draw on top of a canvas element that's already been

I'm currently working with an OpenLayers map that includes WMS layers with time steps. My goal is to create a loop that updates the time for each step and then saves the image once it's rendered. I've been referencing the example code from t ...