Pass either an array, undefined, or the default array as an argument to the function

I am looking to create a function that can accept an array optionally, with the possibility of setting it to a default value if no array is passed.

One common way to do this is:

function myfunc(...values : Array<number>)

While I know how to achieve this, I am unsure of how to allow these types of function calls:

myfunc()
myfunc(1)
myfunc(1,2)
myfunc([1, 2])

Currently, all of the above function calls are supported except for myfunc(). How can I modify the function to accommodate this as well?

Answer №1

If you want to define two overloads and specify the logic in a single function, you can do so with the following code snippet.

function myfunc(...values : Array<number>): number;
function myfunc(values : Array<number>): number;

function myfunc(value : (Array<number> | number), ...values : Array<number>): number {
    if (typeof value === 'number') {
        values.unshift(value);
    } else if (value === undefined) {
        values = [];
    } else {
        values = value;
    }

    // logic

    return values.length;
}

myfunc(); // valid
myfunc(1); // valid
myfunc(1, 2); // valid
myfunc([1, 2]); // valid
myfunc(1, 2, 3, 4); // valid
myfunc([1, 2, 3]); // valid
// myfunc([1, 2, 3, 4], 5, 6); // error
// myfunc([1, 2], [3, 4]); // error

console.log(myfunc(1, 2, 3)) // outputs 3
console.log(myfunc([1, 2, 3])) // outputs 3

In this example, not defining an interface for an array followed by values leads to an error, which is the expected behavior. You can view an example here. It's important to check for undefined as transpiled JavaScript does not account for different function overloads, resulting in a single implementation where value can be undefined.

Answer №2

Take a look at this:

function myFunction(...items : Array<string> | [Array<string>]) {}

myFunction()
myFunction('apple')
myFunction('apple', 'banana')
myFunction(['apple', 'banana'])

myFunction('invalid input')
myFunction(['apple', 'banana'], ['carrot', 'kiwi'])

Click on this link to see the outcome.

Answer №3

Is it possible to utilize this code in a straightforward manner?

function test(input = []) {
    console.log(input)
}

test();
test(1);
test([1]);
test([1, 2, 3]);

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

Arrays in the C programming language are organized into rows and columns using

I'm struggling with the syntax, but I need to create a 2D array with the first element containing pointers to CSTRINGs and the second element being a counter. This is for threading purposes, specifically for passing word lists to threads based on the ...

What's causing the repeated occurrence of ".class expected here"? None of the typical issues seem to be to blame

After reviewing multiple instances, I found that the typical issues stem from code not being within a method or incorrect bracketing. However, I have thoroughly checked for these errors in my code. Here is what I have written: import java.util.*; public ...

Unable to import JSX/TSX component from a separate React application into my primary React application

I find myself facing a challenge with integrating two React applications with different setups. Background: I was assigned the task of developing a design system using ReactJS that would be implemented in their primary application. Despite my limited kn ...

Developing object in place of an array (JavaScript)

After receiving data from the back-end, I handle it within a function: getAgentSuggestionById(agentId) { this._agentsService.getAgentSuggestionById(agentId).subscribe(result =>{ this.agent = result.items.map(e => {let obj = {name: e.name ...

Can TypeScript and JavaScript be integrated into a single React application?

I recently developed an app using JS react, and now I have a TSX file that I want to incorporate into my project. How should I proceed? Can I import the TSX file and interact with it within a JSX file, or do I need to convert my entire app to TSX for eve ...

Creating a function in typescript that returns a type based on the input parameter

type A = { aa: string; bb: number; }; type G = { <T extends keyof A>(a: T): A[T]; <T1 extends keyof A, T2 extends keyof A>(a: T1, b: T2): [A[T1], A[T2]]; // ... }; const g = {} as G; const x = g('aa'); //string const y = g ...

Is it possible to define an array within the fixtures and then use it in the main test case in Cypress? What happens if Cypress Fixture throws a Type

Currently, I am conducting a test case utilizing Cypress fixtures. Within the ../cypress/fixtures folder, I have a userdata.json file. However, every time I attempt to run the test, I consistently encounter this error: TypeError - Cannot read properties of ...

Transmit information between components through a form

Is there a way to transfer data from one component to another in Angular? I have two components set up and I am currently using a selector to display the HTML content in the first component. Now, I need to figure out how to send the data entered in a form ...

Invoke the Jquery core function on the client-side

I need to call a simple function on the client-side event of one of my ASP.NET controls, but I am having trouble doing so. I am new to jQuery... <script type="text/javascript> function UploadStart() { var FileName = $('#ctl00_MainP ...

The 'mat-button' component from Angular Material 2 is displaying as a standard button

Here is my app.component.ts: import { Component } from '@angular/core'; import {MatButtonModule} from '@angular/material/button'; @Component({ selector: 'app-root', templateUrl: './app.component.html', style ...

The attribute 'tableName' is not found within the 'Model' type

Currently in the process of converting a JavaScript code to TypeScript. Previously, I had a class that was functioning correctly in JS class Model { constructor(input, alias) { this.tableName = input; this.alias = alias; } } Howev ...

Issue with Typescript and react-create-app integration using Express

I'm relatively new to Typescript and I decided to kickstart a project using create-react-app. However, I encountered an issue while trying to connect my project to a server using express. After creating a folder named src/server/server.ts, React auto ...

What specific data types should I be using for the $location and $stateParams services?

Currently in the process of redeveloping my AngularJS application (version 1.5) using TypeScript. Can you advise on the types required for injecting the services $location and $stateParams? ...

Combining Repetitive Elements in an Array

Trying to combine an array of products with the same order_id while also including all objects from a second products array. Below are some sample orders: const orders = [ { "order_details": { }, "order_id": "1", ...

Exploring elements within a PHP Multi-Dimensional Array

I am looking to parse the JSON data provided below in PHP using a foreach loop. As a beginner, I could use some guidance on how to achieve this. For privacy reasons, I have only included a limited portion of the data. My ultimate goal is to extract the "i ...

Instructions to load all distinct words from a particular file into an array and showcase them in C++

I'm currently stuck trying to figure out how to identify a unique word within a file. So far, I've managed to load all the words and store them in an array as shown below: char *arr=new char[100]; char ch; fstream my_file("name.txt"); if (!my_fil ...

Display the initial occurrence from the *ngIf statement

Is there a way to display only the first match from the *ngIf? I am currently using an object loop with *ngFor, where I have multiple items with the same Id but different dates. I need to filter and display only the item with the most recent date and avo ...

Search through nested arrays and retrieve elements that match a specific criteria using PHP

Seeking a solution in php, as detailed in the accepted response to this question: javascript - return parent with only child that matches given search string in array of objects with nested object Please see the code snippet below: <?php $items = ...

The name of the OpenLayers geometry is not preserved upon loading from WFS

While using OpenLayers 6 and GeoServer 2.16 (with PostGIS), I encountered a problem where the geometry name of loaded layers from GeoServer gets overwritten. In GeoServer, the geometry name (and column in PostGIS) is defined as geom. The XML response from ...

Exploring how to iterate through an object to locate a specific value with TypeScript and React

I am looking to hide a button if there is at least one order with status 'ACCEPTED' or 'DONE' in any area or subareas. How can I achieve hiding the "Hide me" menu item when there is at least one area with orders having status 'ACCE ...