Typescript's dynamic arguments feature allows for passing varying numbers of parameters without using ell

  // Defining function:
  lm( vv: number, kk: string[] )
  {
    console.log( kk )
  }

  // Invoking the function
  this.lm( 33, ["dd","ff","da"] )

I have thoroughly tested the provided code and it is working flawlessly.

But why do we need ellipses?

Refer to: https://www.typescriptlang.org/docs/handbook/functions.html

function buildName(firstName: string, ...restOfName: string[]) {
    return firstName + " " + restOfName.join(" ");
}

The compiler collects all arguments after the specified parameter following the ellipsis (...) into an array, allowing for flexible usage within the function.

Answer №1

After analyzing your query, it appears that you are comparing two distinct elements. Although both examples lead to the same result on display, they are implemented differently.

Essentially, these represent two separate concepts (syntax) with unique use cases.

  // Defining a function:
  lm( vv: number, kk: string[] )
  {
    console.log( kk )
  }

  // Invoking the function
  this.lm( 33, ["dd","ff","da"] )

and

  // Defining a function:
  lm( vv: number, ...kk: string[] )
  {
    console.log( kk )
  }

  // Invoking the function
  this.lm( 33, "dd","ff","da" )

An instance where ellipsis proves to be more advantageous :

type funcDefinition = (commandName: number, ...params: string[]) => void;

const funcA: funcDefinition = (vv: number, p1: string = 'defA', p2: string = 'defB', ...othersParams: string[]) => {
  console.log(vv, p1, p2, othersParams);
}

const funcB: funcDefinition = (vv: number, p1: string, ...othersParams: string[]) => {
  console.log(vv, p1, othersParams);
}

const funcC: funcDefinition = (vv: number, ...othersParams: string[]) => {
  console.log(vv, othersParams);
}

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

Issue encountered: Jest database test does not end when using testcontainers

I am currently in the process of testing my database within my Node application written in Typescript. I have implemented Postgres 15 and Testcontainers for this purpose. Strangely, my code functions correctly when executed manually, with all clients being ...

Best practices for initializing model objects in a Redux or NgRx application architecture

Context: The development team is currently working on a sophisticated REST-based web application using Angular and the @ngrx library for managing state effectively. In order to represent entities retrieved from the server, such as accounts and users, we ...

Having trouble deploying Firebase Cloud function following the migration to Typescript

After following the steps outlined in the firebase documentation to convert my cloud functions project to TypeScript (see https://firebase.google.com/docs/functions/typescript), I encountered an error when attempting to deploy using 'firebase deploy - ...

Exploring Methods to Define Class Types as Parameter Types in Typescript

Is there a way to pass type information for a class, indicating to the compiler that the provided parameter is not an instance of a class but rather the definition of the class itself? import * as Routes from '../routes'; import * as Entities fr ...

Tips for implementing pagination on a large JSON file without traditional pagination controls

Looking for the best way to implement pagination in a NextJs app that loads products from a local JSON file? This JSON file doesn't have any page properties, so the only option is to limit the number of products shown by using slice: {Object ...

Encountering build errors in .xproj file when working with Type Script in ASP.Net Core

I recently started working on a new ASP.Net Core project and decided to integrate Angular 2 and Type Script by following a blog post tutorial. However, upon adding a Type Script file to my project, I encountered several build errors from the xproj file. h ...

Encountering Error 203 while trying to establish a connection between Angular and Django Rest Api

I'm currently working on a project that involves creating a contacts system, but I've been encountering errors when trying to list them. Interestingly, I can successfully perform CRUD operations using Postman with the API. One of the messages I ...

Encountering a Runtime Exception while utilizing MapQuest's direction routing feature on Ionic 3

I have successfully generated a map using the Ionic 3 framework, but I encountered a runtime error when attempting to use the L.mapquest.directions().route() function. Here are the imports: <link rel="stylesheet" href="https://unpkg.com/ ...

having difficulty interpreting the information from angular's httpclient json request

After creating an Angular function in typescript to make an http request for JSON data and save it to an object, I noticed that the function requires two clicks of the associated button to work properly. Although the connection and data parsing are success ...

Pass the type of object property as an argument in the function

I've been having trouble trying to figure this out and haven't been able to find a solution in the TS docs or examples I came across. Essentially, I'm working with a configuration specifying operations on object properties and looking to en ...

Oops! Looks like you forgot to provide a value for the form control named <name>. Make sure to fill

I have encountered an issue with a nested operation. The process involves removing an offer and then saving it again as a repeating one. However, the problem arises when I try to use patchValue() on the item in offerList[index] after saving the repeating ...

Retrieving information from BlobStorage using Service.ts and triggering the NgOnit function

Within the service.ts module, I am fetching data from Azure Blobstorage and attempting to read its contents. service.ts import { Injectable } from '@angular/core'; import { environment } from '../../environments/environment'; import { ...

Conflicting TypeScript enum types: numbers and numbers in NestJS/ExpressJS

Incorporating types into my NestJS server has been a priority. After creating a controller (a route for those who prefer Express), I attempted to define the type for params: public async getAllMessages( @Query('startDate', ValidateDate) start ...

Utilizing Type Script 1.8 with Visual Studio 2017 for older projects: A step-by-step guide

After installing Visual Studio 2017, I encountered a TypeScript error when trying to run my project. It seems that VS 2017 is using TypeScript 2.1.5, while my application was designed for TypeScript 1.8. Is there a way to make VS 17 utilize TypeScript 1.8 ...

TypeScript combines strong typing for arrays into a unified array of objects

I developed a JavaScript function that can merge multiple arrays into an array of objects based on provided key names. Here’s an example: const mergeArraysToSeries = (arrs, keys) => { const merged = []; for (let dataIndex = 0; dataIndex < arrs ...

How is it that TypeScript still expects a valid return from an overridden method, even when it cannot be reached?

After creating a generic RESTClient with some abstract functions, I encountered an issue where not all REST actions are implemented. In these cases, I wanted to throw an error. The problem arose when trying to override the TypeScript method to both return ...

Typescript's implementation of AngularJs provider

After creating an Angularjs provider in typescript, I found myself wondering if there might be a more efficient way to achieve the same outcome. My current provider serves as an abstraction for a console logger, with the interface primarily designed to s ...

What is a Generic Type in an Array?

Currently, I'm working on designing a mockup app that displays data in the form of buttons in a list. I have successfully implemented most of the features but I have encountered a problem. I have initialized an array and another class to manage the da ...

What is the best approach to re-establish a websocket connection in TypeScript?

Encountering an issue when trying to add a "retry()" method: ERROR in src/app/films.service.ts(28,20): error TS2339: Property 'retry' does not exist on type 'WebSocketSubject'. this.wsSubject.retry().subscribe( (msg) => this. ...

Discovering the steps to showcase _app.tsx within next.js 13 through module federation

I am faced with a situation where I have two Next.js 13 projects: Homepage and Admin Panel. My goal is to showcase the entire Admin Panel (specifically _app.tsx) and embed it within Homepage. To achieve this, I have set up both projects utilizing @module-f ...