Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Different ways to define props in React.FunctionalComponent

Are there any significant differences between those two ways to define props in React.FunctionalComponent?

interface Props {
    username: string,
    age: number
}

const UserPanel: React.FunctionComponent = (props: Props) => (
    <div>{props.username}</div>
);

const UserPanel: React.FunctionComponent<Props> = (props) => (
    <div>{props.age}</div>
);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Yes, a quite significant difference: Option one is throwing away type information.

The function on the right hand side includes information about the props, but then you assign it to a variable that does not have that information. UserPanel‘s type uses the default props of {} so whoever uses UserPanel can not pass in any props. Attempting to pass in a username prop or age prop will throw an error. For example:

const UserPanel: React.FunctionComponent = (props: Props) => (
    <div>{props.username}</div>
);

const SomeOtherCmponent = () => {
  // Error: Type '{ username: string; age: number; }' is not assignable to type 'IntrinsicAttributes'.
  return <UserPanel username="foo" age={100}/>
}

Playground link

You either need to do your second option:

const UserPanel: React.FunctionComponent<Props> = (props) => (
    <div>{props.age}</div>
);

Or you need to do this:

const UserPanel = (props: Props) => (
    <div>{props.age}</div>
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading