0

In my React component, I want to define a property to accept any arbitrary function which returns a value. I do not want to worry about the number of arguments it take.. All that matters to me in the return value of that function.

Some sample expected usages:

<MyComponent getData={function1()}/>
<MyComponent getData={function2(1,2)}/>
<MyComponent getData={function3("hello")}/>

Currently I have defined my component property interface as below.

interface MyComponentProps {
  getData: (...args: any[]) => any;
}

With the above declarations, I get that getData is not a function error in console.

But the below variations work.

<MyComponent getData={() => function1()}/>
<MyComponent getData={() => function2(1,2)}/>
<MyComponent getData={() => function3("hello")}/>

How should I change my type definition so that I can pass any function as a value to the property?

2 Answers 2

1

function1() and function2(1, 2) call functions, so let's say that function1() returns a string. In that case, this would be like getData="some-string" which is indeed not a function.

In the second example, you have a function that itself calls a function.

You could also write these as getData={function1.bind()}, getData={function2.bind(null, 1, 2)}, but I think that using the arrow function as in your second example is preferred.

You could also use named functions as in

function2Caller() { function2(1, 2); }
...
getData={function2Caller}
Sign up to request clarification or add additional context in comments.

Comments

0

Your interface should be:

interface MyComponentProps {
  getData: () => void;
}

this way you can pass any function to getData

1 Comment

I have tried the same as my first try and the results are same.

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.