Course contentsShow
← TypeScript
Lesson 585 of 1,79614. Generics in PracticeFree lesson

Component Props in UI Libraries

Generic component types that adapt based on passed prop configurations.

Component Props in UI Libraries

What You'll Learn

You'll discover how generic component types can adapt their shape based on the props you pass, making UI libraries type-safe and flexible at the same time.

The Core Challenge

Modern UI libraries (like React, Vue, or Svelte) face a common problem: a component's acceptable props often depend on other props you've already passed. For example, a <Button> might accept different props when variant="link" than when variant="button". Generics let you encode these relationships directly in the type system.

How Generics Solve This

Think of a generic component type as a chameleon that changes color based on its environment. The type parameter acts as a switch that transforms the entire props interface.

A common pattern uses a discriminant prop (like variant or as) as the generic parameter. The component's props interface then uses that parameter with conditional logic to determine what other props are valid.

For instance, a Button component might be generic over Variant, where:

  • Variant = "link" requires an href prop
  • Variant = "button" requires an onClick prop but forbids href

The generic parameter flows through the entire props definition, ensuring the component enforces the right constraints based on what variant you chose.

This pattern appears everywhere in modern UI libraries: polymorphic components that change their underlying HTML element, form inputs that vary by input type, or dialog components with different modes.

Why This Matters

Without generics, you'd either accept all possible props (losing type safety) or create separate components for each variant (losing reusability). Generics give you both type safety and a single, flexible component definition.

Key Takeaway: Generic component prop types use type parameters to adapt their interface based on configuration props, enabling type-safe polymorphic components that remain flexible while catching mismatched prop combinations at compile time.