Purus
Purus

Reputation: 5799

Passing any arbitrary function as a property value to Typescript React Component

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?

Upvotes: 0

Views: 648

Answers (2)

Pacxiu
Pacxiu

Reputation: 33

Your interface should be:

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

this way you can pass any function to getData

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191779

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}

Upvotes: 1

Related Questions