Seeking a quick conversion method for transforming x or x[] into x[] in a single line of code

Is there a concise TypeScript one-liner that can replace the arrayOrMemberToArray function below?

function arrayOrMemberToArray<T>(input: T | T[]): T[] {
  if(Arrary.isArray(input)) return input
  return [input]
}

Trying to cram this logic into a ternary operator can get messy, especially when chaining with other operations:

const y = (Array.isArray(input) ? input : [input]).map(() => { /* ... */}) // Hard to follow

The use of Array.concat works in the browser console, but TypeScript throws an error:

const x: number | number[] = 0
const y = [].concat(x)
Error:(27, 21) TS2769: No overload matches this call.
  Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
    Argument of type 'number' is not assignable to parameter of type 'ConcatArray<never>'.
  Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
    Argument of type 'number' is not assignable to parameter of type 'ConcatArray<never>'.

Answer №1

The issue with the concat solution arises from the empty array literal causing a typecheck error. To resolve this, you can modify it as follows:

const arr = ([] as number[]).concat(input);

Another approach is to utilize the flat method instead:

const arr = [input].flat();

This alternative method is not only more concise but also recommended because it does not depend on the concat-spreadable property of the input and explicitly validates arrays.

Answer №2

If you're curious about a more concise approach, consider utilizing the ternary operator:

const convertToArray = <T>(input: T | T[]): T[] => Array.isArray(input) ? input : [input];

Answer №3

After some testing, I believe this code is successful:

let value: number | number[] = 0;
const arrayGenerator = ((): number[] => [])();
const concatenatedArray = arrayGenerator.concat(value);
console.log(concatenatedArray);

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

How to Modify CSS in Angular 6 for Another Element in ngFor Loop Using Renderer2

I have utilized ngFor to add columns to a table. When a user clicks on a <td>, it triggers a Dialog box to open and return certain values. Using Renderer2, I change the background-color of the selected <td>. Now, based on these returned values, ...

Tips for configuring identical libraries under different names

As a Japanese web developer, I struggle with my English skills, so please bear with me. Currently, I am utilizing an npm library. I have forked the library and made some modifications to it. In order to incorporate these changes, I updated my package.js ...

The StreamingTextResponse feature is malfunctioning in the live environment

When I share my code, it's an API route in Next.js. In development mode, everything works as expected. However, in production, the response appears to be static instead of dynamic. It seems like only one part of the data is being sent. I'm puzzl ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

Transform an array containing objects into a single object

Currently exploring the Mapael Jquery plugin, which requires an object to draw map elements. In my PHP code, I am returning a JSON-encoded array of objects: [ { "Aveiro": { "latitude": 40.6443, "longitude": -8.6455, ...

Is it possible to assign multiple ID's to a variable in jQuery?

I am currently using a script for a slider known as Slicebox, and in order to have different image sizes for mobile and desktop views, I need to duplicate the feature on my website. Although it's not ideal, I really like this slider and want to explo ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

Here's a guide on using a button to toggle the display of password value in Angular, allowing users to easily hide

I have successfully implemented an Angular Directive to toggle the visibility of password fields in a form. However, I am facing an issue with updating the text displayed on the button based on the state of the input field. Is there a way for me to dynami ...

Showing additional content in an alternative design

I'm currently facing an issue with the "load more" post button on my Wordpress site. I've designed a unique grid layout for the category page, with a load more button at the bottom. However, when I click the button to load more posts, they appear ...

Is it detrimental to have lengthy jQuery chains?

After extensively utilizing jQuery for quite some time, I recently developed a slideshow plugin for my professional projects. Interestingly, without fully intending to, approximately 75% of the code was written in a single chain. Despite being meticulous ...

Creating a Duplicate of the Higher Lower Challenge Game

To enhance my comprehension of React, I am constructing a replica of the website: Instead of utilizing Google searches, I opted for a dataset containing Premier League stadiums and their capacities. Up to this point, I have crafted the subsequent script: ...

Leveraging Github CI for TypeScript and Jest Testing

My attempts to replicate my local setup into Github CI are not successful. Even simple commands like ls are not working as expected. However, the installation of TypeScript and Jest appears to be successful locally. During the Github CI run, I see a list ...

Can you explain the distinction between using <router-view/> and <router-view></router-view>?

In various projects, I have encountered both of these. Are they just "syntactic sugar" or do they hold unique distinctions? ...

Retrieving data from an HTML input tag and storing it in a variable

I'm currently working on a project that involves reading the contents of an uploaded file through an input tag and storing it in a variable. My goal is to then use an algorithm to decrypt the .txt file: <input type="button" value="decrypt" id="dec ...

Begin a fresh page within a separate window, proceed to print the contents, and subsequently close the window

I am facing some difficulties with this code. I am attempting to use the "onClick" function to change the image once it is clicked, open a new page in a new window, print the newly opened window, and then close it. The issue I am encountering is that while ...

Determine if offcanvas element is visible upon initialization in Bootstrap 5 Offcanvas

I have a search-filter offcanvas div for location and property type on this webpage: On larger screens (desktop), the offcanvas is always visible, but on smaller screens (mobile), it is hidden and can be toggled with a button. This functionality works per ...

jQuery's find method returns a null value

During my Ajax POST request, I encountered an issue where I wanted to replace the current div with the one received from a successful Ajax call: var dom; var target; $.ajax({ type: "POST", url: "http://127.0.0.1/participants", data: "actio ...

Sequentially iterate through elements based on their Data attributes

Assume you are working with HTML elements like the ones shown below <span class="active" data-id="3"> Test 3 </span> <span class="active" data-id="1"> Test 1 </span> <span class="activ ...

Is there a way to extract information from an uploaded file in JavaScript without having to actually submit the file?

Looking for a way to extract data from a user uploaded file using Javascript without page submission? The goal is to process this data to provide additional options in a form on the same page. Any assistance with this would be highly appreciated. ...

What causes the left click to not trigger in Kendo's Angular Charts?

My homepage features a simple bar chart that displays correctly, but I am having trouble capturing the left click event (the right click works fine). This is an example of code from my template: <kendo-chart *ngIf="(dataExists | async)" [ ...