Typescript & React: Manipulating Prop Types
How to use Extend and Pick helpers with generic types, intersection types, and more
This talk tackles how we can handle React prop manipulation in a type-safe way, unveiling some of the more advanced features of Typescript and ensuring that your components — whether ordinary or extended via higher-order components — are fully type safe. Specifically, we will explore:
- Conventional syntax for extending and manipulating props and prop types, giving you more modularity and flexibility typing React components
- Visiting a means of removing unwanted props via utility functions and HOCs, utilising the
Exclude
andPick
helper types to remove type properties we don’t require. As well as conforming types to your props, this also ensures that already-defined props are not overwritten as they travel down your component tree - How generics are used to abstract and manipulate prop types
By the end of this talk you will be equipped with the tools for writing scalable and type-safe prop types within your React projects. Let’s start by reviewing how to format and extend prop types.
Extending prop types
The ability to extend prop types is critical for React components. As projects grow there will be a range of components that utilise an identical subset of props. For example, UI components will inevitably be passing className
and style
, whereas components housing form elements will be passing props like value
, error
, or isSubmitted
. Instead of repeating type definitions for these patters, we can instead abstract them into different types, and combine them where necessary:
type CombinedProps = BaseProps & FormProps
A common solution is to adopt a BaseProps
naming convention for your most fundamental types. ExtendedProps
can come in many forms throughout your project depending on the type of component.
This is particularly useful with HOCs, that can be seen as extensions of another function. A wrapped component’s types will therefore also be extended or modified in some way to adhere to the HOC prop manipulation.