Search⌘ K

Conditional Types Example - React Component Props

Explore how to create TypeScript conditional types that detect if a type is a React component and extract its props using the infer keyword. Understand how to leverage the never type for compile-time validation when types do not match, improving type safety in React components.

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 ...