Encountering a tuple type TypeScript error with a spread argument is far too frequent an occurrence

Encountering this error is becoming a frequent occurrence for me, and I am currently unable to resolve it.

src/graphics.ts:105:55 - error TS2556: A spread argument must either have a
tuple type or be passed to a rest parameter.

105       _queue.forEach((_: any[]) => draw_ctx(this.ctx, ..._))
                                                          ~~~~

Below is the snippet of code where the error arises:

export default class Graphics {

  _queues: any

  constructor(readonly ctx: number) {
    this._queues = {}
  }

  flush() {
      Object.keys(this._queues).map(color => {
      let _queue = this._queues[color]
      _queue.forEach((_: any[]) => draw_ctx(this.ctx, ..._))
    })
  }
}


function draw_ctx(ctx: number, _f: any, r: number, x: number, y: number, w: number, h: number, ...rest: any) {
    console.log('hello')
}

Additionally, provided below is the content of tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ESNext", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,

    /* Linting */
    "strict": true,
    //"noUnusedLocals": true,
    //"noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src"]
}

Answer №1

Arrays and tuples are not the same thing. Tuples have a fixed number of elements, while arrays do not.

TypeScript needs to ensure that the array you pass as an argument meets the requirements of the draw_ctx function.

To satisfy TypeScript, make sure the signature of the _ argument matches the arguments expected by draw_ctx:

_queue.forEach((_:[any, number, number, number, number, number, ...any]) => draw_ctx(this.ctx, ..._))

By defining an array with a fixed number of elements, you can meet TypeScript's expectations.

Note that there are still improvements needed in this code. Instead of casting types, it's better to define proper types like this._queues so that TypeScript enforces correct typing:

export default class Graphics {

  _queues:{[color:string]:[any, number, number, number, number, number, ...any][]}

  constructor(readonly ctx: number) {
    this._queues = {}
  }

  flush() {
      Object.keys(this._queues).map(color => {
      let _queue = this._queues[color]
      _queue.forEach((_) => draw_ctx(this.ctx, ..._))
    })
  }
}

function draw_ctx(ctx: number, _f: any, r: number, x: number, y: number, w: number, h: number, ...rest: any) {
    console.log('hello')
}

link

It may seem like adding

this._queues["crash"] = "this will crash the program in runtime"
works in your code, but results in an error in mine.

Remember: Avoid using any in TypeScript to maintain strong typing. Using any can introduce JavaScript-like issues, undermining the purpose of TypeScript.

Answer №2

The reason for this issue is that the type of _ is any[], causing TypeScript to be unable to match the correct number of parameters for draw_ctx. One way around this is demonstrated below:

draw_ctx(this.ctx, 'foo', 1, 2, 3, 4, 5, ..._)

If needed, you can disable this rule for a specific line by using the following syntax:

// @ts-ignore: A spread argument must either have a tuple type or be passed to a rest parameter.
draw_ctx(this.ctx, ..._)

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

Building Interface/Type with Static Properties and Constructor Signature in TypeScript

I am looking to devise an interface or a type that contains static properties and a constructor signature. My goal is to utilize this interface/type as a parameter for a function. I experimented with using an interface, but encountered limitations in decla ...

There is an issue with types in React when using TypeScript: The type '(user: User) => Element' cannot be assigned to the type '((props: User) => any) & ReactNode'

I'm encountering an error in the terminal and need some assistance. I am not well-versed in TypeScript, so any guidance to resolve this issue would be highly appreciated. https://i.stack.imgur.com/PWATV.png The Loadable component code: import { Circ ...

Encountering the error message "TypeError: Cannot access property 'Token' of undefined" while compiling fm.liveswitch

The fm.liveswitch JavaScript Software Development Kit (SDK) is designed for use with both clients and your own backend "app server". It functions smoothly in the frontend thanks to webpack and babel. However, the same import statement: import liveswitch fr ...

Is it possible to prevent the Virtual Keyboard from automatically appearing on mobile devices?

Whenever a user enters a number on a page component, the Virtual Keyboard on their Mobile device pops up and shifts the entire page. I am looking for a solution to either disable the on-screen keyboard or ensure that the text box remains visible even when ...

react-router: The 'history' type is not found in the current context

Here is some code snippet from App.tsx: interface AppProps{ history: any } export default class App extends React.Component<AppProps,...> { public state = { target: this.props.history.push('/') }; private route() { if (! ...

Execute an Asynchronous Operation in NgRx After Triggering an Action

Please note that this is a question seeking clarification Instructions Needed I am currently working on dispatching an action to NgRx in order to add a task to a list of tasks. Additionally, I need to perform a put request to an API to save the changes ma ...

I seem to be encountering an issue with my Angular 6 HTTP PUT request

Below is the code snippet: products.service: updateCategorie(ucategorie: Icategorie) { const endpoint = this.url + 'api/Category/Edit'; const headers = new Headers(); headers.append('Authorization', 'Bearer ' + localStorage ...

Is it possible to apply JavaScript object destructuring but make changes to certain values before assigning them to a new object?

After receiving movie data from an api, I am currently manually creating a new object with a subset of properties and modified values. Is there a more efficient way to achieve this using javascript/typescript object destructuring syntax? I specifically wa ...

Exploring the possibilities of integrating jQuery into Angular 2 using Javascript

import {Component, ElementRef, OnInit} from 'angular2/core'; declare var jQuery:any; @Component({ selector: 'jquery-integration', templateUrl: './components/jquery-integration/jquery-integration.html' } ...

The element access has been upgraded to utilize ng-content

I attempted to create a tabs component that could be used similarly to Angular Material Component. However, the solution I came up with was flawed and buggy. In this attempt, I utilized document.getElementsByTagName('app-tab'). This is the temp ...

Mastering the usage of Higher Order Components (HOC) with both types of props is

I am facing a challenge in implementing HOCs for this specific scenario. I aim to enclose existing components since they share similar functionalities. Below is an abridged version of my current structure: function CreateComponentHere(props: BaseProps): J ...

Using Nest JS to Handle Null Responses in Services

When using Nest Js to call Axios and get data from the Facebook API, I encountered a problem where the service was returning a null value. Strangely, when I tried calling the response using console.log, it did return a value. Any suggestions on what I migh ...

Align item in center of remaining space within container using Material-UI React

I am relatively new to MUI and styling HTML components, and I have a query. I'm currently utilizing the Grid feature in my React project. My goal is to achieve something similar to this (image edited in Paint, alignment may not be accurate): https://i ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

What is the definition of a type that has the potential to encompass any subtree within an object through recursive processes?

Consider the data structure below: const data = { animilia: { chordata: { mammalia: { carnivora: { canidae: { canis: 'lupus', vulpes: 'vulpe' } } } } }, ...

Creating a dynamic user interface in Angular 6 that successfully tracks changes without reliance on the parent

As I delve into the world of Angular, I am faced with a challenge in creating a reusable component that will be bundled into an npm module. The issue lies in the UI change detection aspect. In order for the component to function properly, the application ...

Sending information to components in Angular using Router

Should I pass data through the angular router to a component, or is it better to use a service? Currently, the component is receiving data in the following way: this.account = activatedRoute.snapshot.data.account ...

TypeScript encounters challenges with implementing Redux containers

I'm struggling to understand the correct way to type Redux containers. Let's consider a simple presentational component that looks like this: interface MyProps { name: string; selected: boolean; onSelect: (name: string) => void; } clas ...

Is it possible for me to incorporate a portion of the interface?

Is it possible to partially implement an interface? export interface AuthorizeUser { RQBody: { login: string; password: string; }; RSBody: { authorizationResult: AuthorizationResult; }; }; class AuthorizeUserRQBody implements Authorize ...

After updating to ionic-native 2.5.1, encountering TypeScript Error TS1005 in Ionic 2

After updating to the latest version of ionic-native (2.5.1) in my ionic 2 project, I am encountering Typescript errors when running "ionic serve" in my terminal. I have attempted to update the typescript version to 2.x but to no avail. Any assistance woul ...