Notbad
Notbad

Reputation: 6296

React functional component with spread operator for props using typescript

How can I use the spread operation to deconstruct the props that are passed down to a component? I have tried some ways to do it without any luck.

import React from 'react';
import "./button.component.css"



function ButtonComponent( {onClick: ()=> void, caption:string, ...otherProps}) {
    return (
        <button onClick={onClick} className="button" {...otherProps}>{caption}</button>
    );
};

export default ButtonComponent;

This is giving following error:

Binding element 'onClick' implicitly has an 'any' type.  TS7031

    4 | 
    5 | 
  > 6 | function ButtonComponent({onClick, caption, ...otherProps}) {
      |                           ^
    7 |     return (
    8 |         <button onClick={onClick} className="button" {...otherProps}>{caption}</button>
    9 |     );

Upvotes: 0

Views: 1720

Answers (1)

Shivam Jha
Shivam Jha

Reputation: 4462

You can first declare an interface, then assign it as type:

interface Props {
  onClick: ()=> void;
  caption:string,
  otherProps: any
}

Then use it:

ButtonComponent( {onClick, caption , otherProps}: Props)

Or it can be used inline:

ButtonComponent( {onClick, caption , ...otherProps}: {onClick: ()=> void, caption:string, otherProps: any})

Upvotes: 2

Related Questions