Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Prop Types vs Typescript

If I use typescript in my project, would that make the usage of prop-types in React obsolete? With prop-types I would have to go through the grunt of defining types but with typescript, this step would be negated. AM I correct in my thinking?

like image 740
Jahil Khalfe Avatar asked Sep 20 '17 14:09

Jahil Khalfe


People also ask

Should I use PropTypes with TypeScript?

Props are required in TypeScript In the prop-types package, all props are optional by default. To make a prop required, you will have to use . isRequired explicitly.

Should I use PropTypes React?

Props and PropTypes are important mechanisms for passing read-only attributes between React components. We can use React props, short for properties, to send data from one component to another. If a component receives the wrong type of props, it can cause bugs and unexpected errors in your app.

Do I need PropTypes with TypeScript React?

PropTypes will help here because they validate data on run time and if some of the data type is wrong then you will get an error that this type is wrong. Using data from a library that may not have adequate or accurate typings, if any.

Should I use interface or type for React props?

Situations for both In case you were wondering, an interface can also extend an object type defined by a type alias and vice versa. Both can even use generic types. These are the common cases in which we define types for objects, especially React prop types. So 95%+ of the time* either one works fine.


1 Answers

Sounds about right. When you use TypeScript you can define the props via an interface.

interface ButtonProps {
  text: string,
  shadow?: boolean
}

const Button: React.FunctionComponent<ButtonProps> = props => {
  return ( /* [...] */ );
};

See here

like image 125
Blackstone4 Avatar answered Oct 05 '22 01:10

Blackstone4