Conditional Types Example - React Component Props
This lesson shows a real-life usage of conditional types in React.
We'll cover the following
Detecting a React component
How can we take advantage of conditional types and use them to extract the types of React component properties? Let’s create a conditional type that checks whether a given type is a React component.
type IsReactComponent<T> =
T extends React.ComponentType<any> ? "yes" : "no";
IsReactComponent
takes a type argument T
and checks whether it extends React.ComponentType
. If yes, it returns a "yes"
string literal type. Otherwise, it returns a "no"
string literal type.
Since React.ComponentType
is a generic type, we had to specify the type parameter for React.Component
, so we provided any
. However, TypeScript lets us do something even cooler; we can use the infer
keyword instead.
type IsReactComponent<T> =
T extends React.ComponentType<infer P> ? "yes" : "no";
Extracting component props type with infer
infer
creates a new type variable, P
, that will store the type parameter of T
if it indeed extends React.Component
. In our case, it will be exactly what we’re looking for, the type of props
! So, instead of returning a "yes"
literal type, it simply returns P
.
type IsReactComponent<T> =
T extends React.ComponentType<infer P> ? P : "no";
Now, we can assume that this type will only be used with actual React components. We’d like the compilation to fail otherwise. Instead of returning "no"
, we want it to return the never
type. It’s a special type that is intended exactly for these situations. We return never
when we don’t want something to happen. If a variable has a never
type, then nothing can be assigned to it.
Get hands-on with 1200+ tech skills courses.