Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS + React - Should props interfaces be exported?

I didn't find any info on this anywhere but I'm curious about best practices.

In my work project I'm currently defining my props interfaces as following:

export interface ExampleComponentProps {
  readonly firstExampleProp: string;
  readonly secondExampleProp: number
}

Does export-ing the interface or readonly-ing members incur a performance overhead during compilation or runtime? Is there any benefit to doing this other than readability and explicitness?

like image 968
Ickerday Avatar asked Mar 01 '23 09:03

Ickerday


1 Answers

  • Yes, export-ing props is a good practice, because it allows more advanced use-cases like wrapping components in another. See the below example.
  • Adding readonly to every property I feel is more a personal preference. Yes, props should never be overwritten within a component, but at the same time this is pretty common knowledge and adding readonly everywhere may be a little superfluous.
import { ExampleComponent, ExampleComponentProps } from "./ExampleComponent";

type WrappedExampleComponentProps = {
  newProperty: string;
} & ExampleComponentProps; 
// I wouldn't be able to this if I weren't able to import ExampleComponentProps

export const WrappedExampleComponent = (props: WrappedExampleComponentProps ) => {
  const { newProperty, ...otherProps } = props;
  return (
      <ExampleComponent {...otherProps } />
      <SideComponent newProperty={newProperty} />
  );
};

In terms of performance: there's definitely no performance hit during runtime, because none of the TypeScript constructs exist at runtime. At compile-time, I'd say the performance hit of these changes are negligible and are outweighed by its advantages (e.g. extensibility).

like image 141
Martin Devillers Avatar answered Jun 03 '23 17:06

Martin Devillers