What is the reason that the spread argument does not function for every type?

Here is a code snippet I found on the TypeScript Playground:

function foo(a: number, b: number) {}

const msg: any = {
    params: [1,2],
};
// None of these works:
foo(...msg.params); // This should work but it doesn't
foo(...(msg.params as any));
foo((...msg.params) as any);

// Only this works:
(foo as any)(...msg.params);

The error message is:

A spread argument must either have a tuple type or be passed to a rest parameter.

msg/msg.params are already any. Why can't I use it for spread ... operator and pass as function argument? Isn't it the point of any? And why does casting the function to any works?


The forced compiled Javascript works:

"use strict";
function foo(a, b) {
    console.log(a + b);
}
const msg = {
    params: [1, 2],
};
foo(...msg.params); // Logs 3 correctly

Answer №1

When you define the function foo, it is specified to expect exactly two arguments of type number. This means that typescript will prevent you from passing a different number of arguments to it.

If you are unable to modify your msg variable to add the correct typing, there are several ways to work around this issue:

  1. One option is to cast foo to any, which effectively disables the typescript check and explains why no error is shown in your example,
(foo as any)(...msg.params);
  1. Another approach is to cast the argument to a tuple such as [number, number] or even [any, any],
foo(...(msg.params as [number, number]));
foo(...(msg.params as [any, any]));
  1. You can also directly pass the element instead of using the spread operator, for example msg.params[0].
foo(msg.params[0], msg.params[1]);

To see an example of these solutions in action, visit this link.

However, it is important to note that using any should be avoided as it essentially disables type checks and can lead to errors, as mentioned by others in the comments. The recommended solution is to redefine the function or variable with the correct types — refer to the provided link for an example of how to do so.

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

Calculating the total of all values in a table

For my ngFor loop, the invoice total is calculated based on price and hours, but I also want to calculate the totals of all invoices in the end. <tr *ngFor="let invoice of invoiceItem.rows"> <td>{{ invoice.rowName }}</td> <td& ...

What is the process for inputting a value within single quotation marks?

I'm working with a code snippet that looks like this: for(var j=0; j < this.arr.length; j++) { arr.push({ id: 'j', label: this.arr[j], display: () => this.arr[j] }) } I am curious about ho ...

Error: The AJax function is not defined

I keep encountering an issue while attempting a basic $.ajax call to giphy. The error message that keeps popping up is: index.html:32 Uncaught TypeError: $.ajax is not a function The code snippet I am currently executing is posted below. Can someone ...

When incorporating TypeScript, always remember to indicate any missing attributes, such as rawBody

When I compile my code, I encounter this console error: The 'rawBody' property does not exist on the 'Request' type. This error occurs specifically on this line of code: busboy.end(req.rawBody); According to these docs, the 'ra ...

Checking the types for object literals returned from Array.map functions

Check out this demonstration I made in the TypeScript playground: interface Test{ a: string b: string } const object: Test = { a: 'b', b: 'c', } function testIt(): Test[] { const data = [{b: '2', c: &apo ...

What steps can I take to stop typescript tsc from compiling the ../node_modules directory?

I'm currently working on a project and I decided to clone the typescript/node/express sample project into a subfolder. However, when I try running tsc -p . in the sub-folder, I encounter compilation errors because tsc is scanning ../node_modules. Is t ...

If the FedEx function does not receive a payment, it will need to return a value of Payment Required

I am struggling with understanding functions, parameters, and arguments in JavaScript as I am new to it. My goal is to have a function that returns different values based on the payment amount. If no payment is passed, it should return "Payment Required", ...

Looking to display parent and child elements from a JSON object using search functionality in JavaScript or Angular

I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data: [ { "name": "India", "children": [ { "name": "D ...

When accessing APIs, create an array of observables for each user call and then trigger a function once all are successfully resolved

As I aim to generate a list of observables while a user engages with the webpage, I am faced with the challenge of individually subscribing to each observable, but desiring another function to execute after individual or multiple simultaneous API calls are ...

Extending an External Object with Custom Properties in TypeScript

When working with an external library, I often find myself needing to add new properties to passed-in parameters. Instead of using (<any>conv.data) due to the compiler error Object is of type 'unknown', I'm curious if there's a mo ...

Is there a method to alter the type of the initial parameter in an enhancer function?

Introducing a fantastic higher order function called logFunctionName that elevates the original say function by logging its name. This incredible feat is accomplished by the enhanced enhancedSay function, which mirrors the arguments of the initial say func ...

Filtering rows in angular based on the current data's id

currData = { id: "iStyle1", status: "PENDING" }; data = [ { id: "splitStyle1", rows: [ { id: "1cUMlNRSapc5T", row: 2, sequence: 2, status: ...

Verify whether the message received contains a specific text within the property

Currently, I am facing a challenge with displaying a specific div in my component template only if any incoming messages contain the TYPE_OTHER property. With numerous variations of the TYPE_OTHER identifier, I am pondering on creating a condition that can ...

Can a blob file be transformed into base64Data using Javascript specifically in Ionic and Angular frameworks?

https://i.stack.imgur.com/3aMyx.png[ async FileZip() { const code = await fetch("./assets/input.txt") var blob = await downloadZip([code]).blob() console.log(blob); function blobToBase64(blob: Blob): Observable<string> { r ...

What is the prescribed interface or datatype for symbol type in TypeScript with JavaScript?

I have a set of symbol values in JavaScript that I want to convert to TypeScript. // Defining object values in JavaScript const size = { Large: Symbol('large'), Medium: Symbol('medium') } What is the most efficient method to conv ...

Issue: An object with keys {} is not suitable as a React child, causing an error

I am new to TypeScript and seeking help from the community. Currently, I am working on a to-do list project where I am using React and TypeScript together for the first time. However, I encountered an error that I cannot decipher. Any assistance would be g ...

Issue: Data authentication failure due to unsupported state

I encountered an error message while executing the code below. Error: Unsupported state or unable to authenticate data at Decipheriv.final (node:internal/crypto/cipher:196:29) at decrypt (/Users/username/dev/playground/node/src/index.ts:14:65) import cr ...

ESLint is reporting an error of "Module path resolution failed" in a project that includes shared modules

Encountering ESLint errors when importing modules from a shared project is causing some frustration. The issue arises with every import from the shared/ project, presenting the common ESLint import error: Unable to resolve path to module 'shared/hook ...

Warning: The socket has already emitted an error event. Make sure to use the destroy method on the socket when dealing with a 'clientError' event

After configuring a new Vue 3 app with the specified choices: npm create vue@latest ✔ Add TypeScript? … Yes ✔ Add JSX Support? … No ✔ Add Vue Router for Single Page Application development? … Yes ✔ Add Pinia for state management? … Yes ✔ ...

Enhancing Data Retrieval in Next.js: Implementing Typed Requests and Responses with the Fetch API

Context I've been developing a web application using Next.js and a custom Django Python backend, but I am struggling to find an efficient approach for making API requests from my frontend to the backend. My main goal is to centralize the logic for fet ...