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

Exporting from Excel is causing dates and times to be displayed as numbers instead

Having trouble with a specific date while exporting an Excel file. Refer to the screenshot of the Excel file for clarity: https://i.stack.imgur.com/7mFE4.png The date '01/02/2019 00:00:00' is being treated as a number instead of displaying corre ...

Angular2 has encountered a malfunction with the chart feature

My attempt to create a Bar Chart with this GitHub repository is not working in Chrome. You can view my code on Plunker. Can someone help me identify the issue? Below is the updated code: app.ts import {Component, Pipe, PipeTransform} from 'angular2 ...

Restrict or define the acceptable values for a key within an interface

In search of defining an interface that allows for specific range of values for the key. Consider this example: interface ComparisonOperator { [operator: string]: [string, string | number]; } The key can take on values such as >, >=, !=, and so ...

What is the best way to make two buttons align next to each other in a stylish and elegant manner

Currently, I am diving into the world of glamorous, a React component styling module. My challenge lies in styling two buttons: Add and Clear. The goal is to have these buttons on the same row with the Clear button positioned on the left and the Add button ...

Having trouble with React throwing a SyntaxError for an unexpected token?

Error message: Syntax error: D:/file/repo/webpage/react_demo/src/App.js: Unexpected token (34:5) 32 | 33 | return ( > 34 <> | ^ 35 <div className="status">{status}</div> 36 <div className=&quo ...

Angular 2: The linting error shows up as "Anticipated operands need to be of the same type or any"

So, I have this shared service file where a variable is defined like so: export class SharedService { activeModal: String; } Then, in my component file, I import the service and define it as follows: constructor(public sharedService: SharedService) ...

Entering the appropriate value into an object's property accurately

I am currently facing an issue with typing the value needed to be inserted into an object's property. Please refer below. interface SliceStateType { TrptLimit: number; TrptOffset: number; someString: string; someBool:boolean; } inter ...

deliver a promise with a function's value

I have created a function to convert a file to base64 for displaying the file. ConvertFileToAddress(event): string { let localAddress: any; const reader = new FileReader(); reader.readAsDataURL(event.target['files'][0]); reader ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

typescript add some flair to the setter function

I'm attempting to enhance a setter function within a class in the following manner: export class SearchResultSortBy{ private sortByChoice; constructor() { ...} /* getters & setters */ get sortBy() { return this.sortByCh ...

What is the best way to exclude a particular subtype or property?

Is there a way to exclude a specific nested property? Let's take a look at an example. interface ILikes { article: string, page: string, userId: number | string, } interface IUserData { userName: string, isAdmin: boolean, ...data, ...

Retrieve input value in Angular 8 using only the element's ID

Can the value of an input be obtained in Angular 8 with TypeScript if only the element's id is known? ...

When it comes to passing prop values through functions, TypeScript types do not provide suggestions

I'm struggling to find a way to ensure that developers have suggested types for specific props in my component, regardless of how they pass data to the prop. For example, when I directly pass an array of values to the prop: <Component someProp={[{ ...

There is a chance that the object could be 'undefined' when attempting to add data to it

I created an object and a property called formTemplateValues. I am certain that this property exists, but I am getting an error message saying: "Object is possibly 'undefined'". It should not be undefined because I specifically created it. Why am ...

Is there a method to accurately pinpoint the specific type?

Is there a way to optimize the validateField function to narrow down the type more effectively? type TStringValidator = (v: string) => void; type TNumberValidator = (v: number) => void; type TFields = 'inn' | 'amount'; interface ...

Creating a fresh type in Typescript based on object keys that are already defined within an interface

Here is the scenario I am currently dealing with: interface ListField { code: number; message: string; } interface List { [key: string]: ListField; } export const allCodes: List = { FIRST: { code: 1, message: 'message 1', }, ...

Chrome stack router outlet and the utilization of the Angular back button

I'm experiencing an issue with the back button on Chrome while using Angular 14. When I return to a previous page (URL), instead of deleting the current page components, it keeps adding more and more as I continue to press the back button (the deeper ...

Update a specific element within Angular framework

Just starting out with angular and facing a seemingly simple issue that I can't seem to solve despite trying various solutions found on SO. I have created a login component where upon submission, the user is redirected to their profile page. While I a ...

Error TRPCClient: The unexpected presence of the token "'<'", ""<!DOCTYPE "... invalidates the JSON format within Next.JS

Encountering an error in the authentication call back page: TRPCClientError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON in Next.JS. The issue occurs in src/app/auth-callback/page.tsx and here's the relevant code ...