Home > OS >  Add typing for function component in React JS
Add typing for function component in React JS

Time:06-24

I noticed that some of developers type react js functional component like this:

const Result: React.FC<ResultProps> = ({ prop1, prop2 }: ResultProps) => {

I don't understand the idea, why they use ResultProps 2 times. Is not enough to type the component in this way:

const Result: React.FC<ResultProps> = ({ prop1, prop2 }) => {

?
What is the difference between these 2 ways of typing? I tried both implementation and got the same result.

CodePudding user response:

Is not enough to type the component in this way:

Yes, that's enough. You don't have to repeat the type of the props, this is just fine:

const Result: React.FC<ResultProps> = ({ prop1, prop2 }) => {
    // ...
};

Playground link

That works because you've already set the type of Result, so TypeScript knows what parameters the function accepts and their types.


A note about React.FC: In the types for React v17.x and below, when you used React.FC for your component, you were saying it supported children. Your component doesn't support children, so I thought I should call it out. Many people started saying not to use React.FC for this very reason: it was easy to accidentally give your component the wrong type information. But in React v18.x and above, they changed the definition of React.FC so that it no longer assumes your component supports children. (If you want to say it does, you add PropsWithChildren like this: React.FC<PropsWithChildren<ResultProps>>.)

So if you're using v17.x or below and you don't want the component to say it supports children when it doesn't, here's an alternative way to do the types for it that you often see:

const Result = ({ prop1, prop2 }: ResultProps) => {
    // ...
};

Playground link

Note, though, that that relies on you returning the correct thing from the component, since there's no return type annotation TypeScript can use to help you if you forget to return something or return something that isn't valid for a component (like returning a plain object). So you might include a return type as well:

const Result = ({ prop1, prop2 }: ResultProps): JSX.Element => {
    // ...
};

Playground link

But again, in the types for React v18.x, React.FC no longer assumes your component supports children.

  • Related