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

Organizing React Component Props in TypeScript

I just started using TypeScript and I’m wondering what the best approach is when defining Component Props. Say I have a component called ‘Entry’ that looks like this:

interface EntryProps {
  id: string;
  label: string;
  dateAdded: Date;
  isComplete: boolean;
}

const Entry = ({ id, label, dateAdded, isComplete }: EntryProps) => {
  // return some JSX
};

This seems fine to me, but where I get confused is when multiple components need to know the structure of the Entry interface. Say I have an ‘EntriesList’ Component that takes in an array of Entries as a prop, and I have a backend call that needs to return an array of Entries. Should I extract the EntryProps interface into its own module, perhaps in a folder called ‘models’, and then have the Entry Component take in a single prop ‘entry’ of type ‘EntryInterface’? Or is it not a good practice to have the props for the Entry component defined outside of the actual Component file? I suppose I could export the EntryProps from the Entry Component file but then the name ‘EntryProps’ seems a little misleading.

If anyone has tips on the subject, I’d really appreciate it, thank you.

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

>Solution :

First, a better way to declare props is like this:

interface EntryProps {
  id: string;
  label: string;
  dateAdded: Date;
  isComplete: boolean;
}

const Entry: React.FC<EntryProps> = ({ id, label, dateAdded, isComplete }) => {
  // return some JSX
};

This way, any default props like children are included.

I would keep props interfaces separate from API response interfaces, even if they are identical. You could have something like this:

interface Entry {
  id: string;
  label: string;
  dateAdded: Date;
  isComplete: boolean;
}

interface EntryResponse extends Entry {}

interface EntryProps extends Entry {}

At the moment, all of these things may be identical but this approach gives you more flexibility to differentiate later if necessary.

Another good thing to do is move your types into a types.d.ts file. This keeps your code from being too cluttered and .d.ts files are not transpiled, which probably offers some minimal efficiency improvement.

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