0

Is it just using React.FC type?

import React from 'react'

const MyComponent: React.FC = () => (
  ...
);

export default MyComponent;

2 Answers2

2

Yes, you can also use FunctionComponent. FC is literally just an alias for that. SFC is being deprecated.

Chris B.
  • 5,477
  • 1
  • 12
  • 30
1

When it comes to using React Functional components with TypeScript, you should define generics and use it with your function components.

This will provide an extra layer of safety when building components, thus allowing you to discover errors more quickly.

interface MyProps {
  value: string,
}

const MyComponent: React.FC<MyProps> = (props) => {
  const { value } = props;

  return <span>{value}</span>;
}

Similarly, you can use generics for general React components.

wentjun
  • 40,384
  • 10
  • 95
  • 107
  • If I add that generic type, is it still necessary to add the `MyComponent.propTypes`? – Rannie Aguilar Peralta Sep 14 '19 at 03:28
  • Neither one is strictly necessary, however propTypes has the advantage of being checked when the code is run as opposed to only in development like TypeScript. TS only really exists in development for catching errors, but is compiled down to plain browser ready JS when it's deployed. PropTypes, however, persist after compilation and can give an extra layer of type safety in practice when your application is dealing with data from external sources, like an API or a user themselves. For maximum type safety, use both, but it depends on how much security your app needs in that regard. – Chris B. Sep 14 '19 at 03:33
  • @RannieAguilarPeralta In your case, there is not much of a use to maintain both `propTypes` and TypeScript interface/generics. This is because your logic seems rather "internal", and interfaces would have caught the errors on compile time. However, you may need to use `propTypes` as well, if you are actually packaging your application and publishing it as a `npm` package, as typechecking will need to be done at run time since data will come externally with insufficient typechecking – wentjun Sep 14 '19 at 03:33
  • There is a detailed discussion on `propTypes` vs TS `interfaces` at this stackoverflow post: https://stackoverflow.com/questions/41746028/proptypes-in-a-typescript-react-application – wentjun Sep 14 '19 at 03:34