Paul Michaels
Paul Michaels

Reputation: 16685

ReactJS typescript error Parameter props implicitly has 'any' type

Following, and adapting the tutorial here, I've hit a snag when trying to define a function to render some HTML.

function Toolbar(props) {
    return (
        <div>
            <button onClick={() => props.onClick()}>Refresh</button>
        </div>
    );
}

This errors in Typescript, because props is not defined. I understand why I'm getting the error, but what I'm missing is what type should props be?

I believe I should then be able to use this inside another component like this:

function App() {
    return (
        <div>
            <Toolbar onClick={() => alert('hello world')}>Test</Toolbar>
        </div>
    );
}

And the props is just whatever I specify. This would seem to be borne out here: although that link doesn't mention typescript. So, my question is: how does this feature (that of passing properties into a function or class) work with typescript when, by definition, you don't know what you're passing through?

Upvotes: 14

Views: 22341

Answers (1)

Peter Ambruzs
Peter Ambruzs

Reputation: 8213

You should define an interface for the props.

interface Props {
   onClick: () => void;
}

function Toolbar(props: Props) {
   return (
       <div>
           <button onClick={() => props.onClick()}>Refresh</button>
       </div>
   );
}

I also like to define my functional components as an arrow function. And you can use the FC (Functional Component) type definition with the Props generic type. This way you can deconstruct your properties right away.

const Toolbar: React.FC<Props> = ({onClick}) => {
   return (
       <div>
           <button onClick={() => onClick()}>Refresh</button>
       </div>
   );
}

Upvotes: 23

Related Questions