Using a function as a parameter in Typescript: Anticipated no arguments, received 1.ts

I'm encountering an issue when trying to pass the doSomething function into performAction. The error message I'm receiving is Expected 0 arguments, but got 1

interface SomeInterface {
  name: string,
  id: string
}

function doSomethingFunction(props: SomeInterface) {
  console.log(props.name + " " + props.id);
}

function performAction(doSomething: () => void) {
  doSomething({
    name: "foo",
    id: "bar"
  });
}

performAction(doSomethingFunction);

Is my syntax correct for Typescript?

Answer №1

There seems to be an issue with the doSomething type. The type declaration - () => void specifies that it takes no arguments, but later on, arguments are being passed to it.

For the provided code snippet, the following adjustment would work, however, the specific arguments and their types for doSomething should be determined based on the context. Consider using an interface if you have an abstraction in mind.

function performAction(doSomething: (stuff: { name: string, id: string }) => void) {
  doSomething({
    name: "foo",
    id: "bar"
  });
}

Click here for a demonstration.

If the term string in your code is a variable, it should be changed as string is a reserved type. If you're unsure about fixing the type of doSomething currently, you can utilize the Function type. View demo here.


Update

For the revised question, you should define

function performAction(doSomething: (stuff: someType) => void
Demo available here.

Answer №2

Define a function called doSomething without any arguments: doSomething: () => void. Instead, consider changing it to

doSomething: (arg: SomeInterface) => void
where SomeInterface is defined as {name: string; id: string;}.

Answer №3

let x = 6;
let y = 2;

let result = calculate(operation, x, y);
console.log(result);
result = calculate(sum, x, y);
console.log(result);

function calculate(operation: Function, x: number, y: number): number {
    return operation(x, y);
}

function operation(valueX: number, valueY: number): number {
    console.log('Performing an operation');
    return valueX - valueY;
}

function sum(valueX: number, valueY: number): number {
    console.log('Performing addition');
    return valueX + valueY;
}

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

Tips for creating a custom Menu with content overflow in a single direction

What is the goal of this task? I have developed a custom Menu in my application with 8 options. There is a need to dynamically disable certain menu options based on specific conditions (e.g. disabling the last 4 options). When a user hovers over a disable ...

Accessing a specific element within an array that has been nested within another array, using JavaScript

Here's what my code looks like: planets[0]= new THREE.Mesh( geometry, material ); planettexts[0]= new THREE.Mesh( textGeometry, textMaterial ); planets[0].add(planettexts[0]); Now, I am trying to hide the planettext, but every attempt results in an ...

Tips for looping through every item that has a specific class name

I have tried various methods and researched numerous ways to achieve this, but I am struggling to implement it in my code. My goal is to iterate through each <li> element and check if the text inside the <span class="state"> tag is ei ...

What is the process for updating the combination selector for each product within a specific category in PrestaShop 1.7?

We have a range of products in a specific category, each offering multiple pack sizes with varying prices (e.g. 1, 3, 5, 10, 25, 50, 100). EDIT: The homepage features these products displayed using an owl-carousel within a div element: https://i.sstatic.n ...

`Can incompatible Typescript types be allowed for assignment?`

Currently, I am faced with the challenge of sharing type definitions between my server and front-end. These definitions are stored in a separate npm package that both installations utilize. The issue arises on the front-end where variables containing Objec ...

Removing a targeted element from an array in Angular

After receiving a JSON array object in Angular using TypeScript, I am attempting to remove a specified object from it. However, my attempts at deletion have been unsuccessful. addCategorySub(categorySub: CategorySubModel, index: number) { categorySub.id ...

The authentication0 router fails to initiate navigation

I'm currently using Auth0 in combination with Angular 2. The issue I am encountering is that my login code isn't redirecting to the home page after authentication. Based on my understanding, Auth0 does not handle the redirection process itself. ...

Modify the paragraph's class upon clicking the radio button

I have been struggling with changing the color of <p> based on the radio button selected using two classes, red and blue. However, for some reason, it's not working as expected. If anyone has any insights or suggestions on how to fix this issue ...

Is it possible for Vue data to be handled asynchronosly

Have you ever wondered? Is it possible for Vue's data function to be asynchronous? Imagine needing to fetch data from an API using a library like axios, which only offers async methods. How can this data be loaded into Vue's data function? Con ...

WebStorm disregards tsconfig compiler directives when working with Angular applications

My project structure was created using angular-cli, which includes a root tsconfig.json, src/tsconfig.app.json, and src/tsconfig.spec.json. Despite having the noImplicitAny and strict options enabled in the root configuration, I do not receive error notifi ...

React approach for managing multiple combobox values

Currently, I'm working on a page where users can upload multiple files and then select the file type for each file from a dropdown menu before submitting. These 'reports' are the uploaded files that are displayed in rows, allowing users to c ...

Send information from the textbox

I am trying to extract data from an input field and use it to create a QR code. While passing the value as text works, I am facing issues with passing the actual input value. Does anyone have a straightforward example of this process? import React, {Comp ...

Instead of using a hardcoded value, opt for event.target.name when updating the state in a nested array

When working with a dynamically added nested array in my state, I encounter the challenge of not knowing the key/name of the array. This lack of knowledge makes it difficult to add, update, iterate, or remove items within the array. The problem lies in fun ...

When launching JQuery UI Tabs in a new browser tab using ajax, the HTML from the ajax response will be immediately shown

I am currently in the process of upgrading from JQuery UI 1.8.14 to JQuery UI 1.10. Previously, when using v1.8.14 code, opening a tab in a new browser tab would cause the entire page to reload, activating the default tab (tabIndex=0). However, I am faci ...

Arranging strings in descending order using Typescript

I was attempting to arrange a string[] in a descending order. This is what I have come up with so far: let values = ["Saab", "Volvo", "BMW"]; // example values.sort(); values.reverse(); Although this method is effective, I am wondering if there is a mo ...

Encountering the error "Vue 2.0 encounters an undefined push during router.push

I'm currently working on a project that involves implementing a function to route the list of subMenus displayed by the mainMenu. Each subMenu is identified by its specific name, which I would like to append and use as the route path that I am aiming ...

The react-redux developer tool appears to be disabled and is not displaying the current state of the application on the extension toolbar

Just finished the redux-tutorial and attempting to view the state in the redux-devtools. However, the redux-devtools seems to be inactive on the extensions bar. Upon clicking it, a menu appears with options like "to right, to left etc". Selecting one of ...

Wordpress tabs with dynamic content

I came across a code on webdeveloper.com by Mitya that had loading content tabs and needed the page to refresh after clicking the tab button. It worked perfectly fine outside of WordPress, but when I tried implementing it into my custom theme file, it didn ...

My ng-view html is unexpectedly displaying as plain string. What steps should I take to resolve this issue?

Why is my ng-view HTML displaying as plain text? How can I resolve this issue? I have encountered an error, here is the screenshot for reference: Unfortunately, I am unable to upload images at the moment. ...

Use JavaScript to overlay drawings onto an existing image

Within this particular image, I possess a compilation of pixel coordinates outlining the polygon segments that encompass all the objects contained within it (refer to the image provided below). For example, in relation to the individual, there exists a li ...