简体   繁体   中英

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 |     );

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM