Issue
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
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}/>
}
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>
);
Answered By - Nicholas Tower
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.