Muljayan
Muljayan

Reputation: 3886

Best practice for type checking props in Typescript with React

Below I have two variations of type checking props in React when used with Typescript.

Variation 1

interface Props {
  prop1: string,
  prop2: string,
}

const MyComponent = ({ prop1, prop2 }: Props) => {
  return (
    <></>
  );
};

Variation 2

interface Props {
  prop1: string,
  prop2: string,
}

const MyComponent: React.FC<Props> = (props) => {
  const { prop1, prop2 } = props;
  return (
    <></>
  );
};

Which of the above variations is considered best practice and why?

Upvotes: 1

Views: 636

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53884

Aside from typing the props of function component, you can type with React.FC/React.FunctionComponent (they are the same, just shorthand) as your second example.

Some differences are:

  • React.FC is explicit about the return type, while the normal function version is implicit (or else needs additional annotation).
// Implicit return type
const MyComponent = ({ prop1, prop2 }: Props) => {
  return (
    <></>
  );
};
  • It provides type checking and auto-complete for static properties like displayName, propTypes, and defaultProps.
// Typing MyComponent.
// Will autocomplete `displayName`, `propTypes`, `defaultProps` etc
  • It provides an implicit definition of children
// Implicit definition of children property
const MyComponent: React.FC<Props> = ({ children, prop1, prop2 }) => {
  return (
    <></>
  );
};

Which of the above variations is considered best practice and why?

Usually React.FC is used for typing a function component, the common sense is to differ it from a "function which returns React element", which resembles the first variant.

// Some helper function which returns React element
// But not a component like the first variant
const helperFunction = (args:Args) => {...}
// ^ typing with React.FC will give it a meaning of function component

Upvotes: 1

Related Questions