Mikhail Batcer
Mikhail Batcer

Reputation: 2065

Why do I need to extract props type definition into a type / interface?

Suppose I have a functional component:

const MyText = ({ value }) => (
    <div className="my-fancy-text">{value}</div>
);

Now in Typescript I need to add typing, and the simplest way is like this:

const MyText = ({ value }: { value: string }) => (
    <div className="my-fancy-text">{value}</div>
);

But I see that most people would extract props type like this:

type MyTestProps = {
    value: string;
};

const MyText: React.FC<MyTestProps> = ({ value }: MyTestProps) => (
    <div className="my-fancy-text">{value}</div>
);

Why? Is it so for us to

P.S. I honestly tried to find an answer, but didn't succeed.

Upvotes: 0

Views: 49

Answers (1)

fast-reflexes
fast-reflexes

Reputation: 5186

I would say that this style is best practice and it's good to do it in general for complex argument types in Typescript because:

  1. If you use the type as argument in many places, you avoid repeating the whole type definition everywhere. Likewise, if you want to change something in your type, you can do it in one place instead of several.

  2. You can export the interface or type for use elsewhere whereas you can't export an inline type in an argument (or you can with typeof in the case of React components but not arbitrarily with any inline arguments).

  3. It's more structured to keep long type definitions separate and it's easier to keep function signatures tidy.

  4. If you name your types, you can use names that signal what the type is used for / consists of. Let's say you have a table component that takes data and table headers and optionally colors on cells; creating types for these purposes and naming them properly both make the API more clear to use and someone watching your code get more hints about your code than with inline types.

  5. If you want to create a supertype, you can reuse a named type like interface Super extends Sub or create an intersection type type Extra = {} & Base. This cannot be done arbitrarily with inline types.

There are probably more motivations and even though all of them do not necessarily apply to React components, they do apply to Typescript types in general and thus, even only for consistency, named types is a good practice in this area too.

Upvotes: 2

Related Questions