19

I am trying to pass in this doSomething function into performAction, but the error I'm getting is Expected 0 arguments, but got 1

type someType = {
  name: string,
  id: string
}

function doSomethingFn(props: someType) {
  console.log(props.name + " " + props.id);
}

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

performAction(doSomethingFn);

Am I using the proper syntax for Typescript?

3 Answers 3

20

The doSomething type seems incorrect. In the type declaration – () => void it takes no arguments, but later you are passing arguments to it.

For this piece of code following would work, but you would know better what should be the arguments and their types of doSomething. Probably use a interface if you already have an abstraction in your mind.

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

Demo for above.

Also if string in your code is a variable you need to change that because string is reserved for the type. In case you don't what to fix the type of doSomething right now you can use the Function type. Demo


Update

For your updated question you need to write function performAction(doSomething: (stuff: someType) => void Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Is there any way to make it generic?
4

You type doSomething as a function with no arguments: doSomething: () => void. Make it, dunno, doSomething: (arg: SomeInterface) => void (SomeInterface being, for example, {name: string; id: string;}).

Comments

0
let a = 6;
let b = 2;

let res = outer(substr, a, b);
console.log(res);
res = outer(addit, a, b);
console.log(res);

function outer(inner: Function, a: number, b: number): number {
    return inner(a,b);
}

function substr(vala: number, valb: number): number {
    console.log('We are substracting');
    return vala - valb;
}

function addit(vala: number, valb: number): number {
    console.log('We are adding');
    return vala + valb;
}

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.