0

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

1 Answer 1

2

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})
Sign up to request clarification or add additional context in comments.

2 Comments

So, I can't mix the var declarations with their types as I did? I must always specify the descontruction variables and then their types? I swear I saw something more like the code I added. And I really prefer it. It is much compact.
You can do like this when you are receiving props without de-structuring, but not like this

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.