Hello! Welcome to the final lesson of our module on Advanced Component and TypeScript Patterns.
In our last lesson, we explored the powerful headless component pattern, learning how to separate a component's behavioral logic from its visual presentation. This separation gives us incredible flexibility. Today, we'll learn how to manage the complexity that comes with that flexibility by mastering one of TypeScript's most advanced features.
Our goal is to use conditional types in TypeScript to create advanced, dynamic prop types. This will allow us to build component APIs that are not only flexible and intuitive but also perfectly type-safe. We'll define props that intelligently adapt based on the values of other props, eliminating entire classes of bugs at compile time.
The Power of Dynamic Props
Imagine a component whose props change based on how it's used. For example:
- A
Buttoncomponent that requires anhrefprop when used as a link, but anonClickhandler when used as a button. - A
Panelcomponent that can havecollapsibleanddefaultCollapsedprops, but only if thecollapsibleprop is actually provided. - A generic
Dropdowncomponent that accepts an array of strings, but if you give it an array of objects, it then requires you to specify which object keys to use for the label and value.

These scenarios are impossible to type correctly with basic interfaces or unions alone. They require a way to express a logical relationship within the type system itself. This is where conditional types come in.
1. Understanding Conditional Types
At its core, a conditional type in TypeScript uses a ternary-like syntax to make a decision at the type level.
Documentation - Conditional Types
Let's start with the official TypeScript documentation to understand the fundamental syntax and concept of conditional types.
Please read the introduction and the section that follows it. Focus on: The basic syntax: SomeType extends OtherType ? TrueType : FalseType; How this construct allows you to create a type alias (like NameOrId) that simplifies function overloads by encoding the selection logic directly into the type system.
As you saw, the syntax is T extends U ? X : Y. If type T is assignable to type U, the resulting type is X; otherwise, it's Y.
Given your background, you can think of this as an if/else statement for types. This simple construct, especially when combined with generics, unlocks immense power.
2. Pattern 1: Mutually Exclusive Props
A common requirement is for a component to accept one set of props or another, but not a mix of both. For instance, a Button might accept a text label or an icon, but not both simultaneously. We can enforce this with a union of specific types, using the never type to "forbid" a prop.
This video provides an excellent, practical walkthrough of this and other conditional prop patterns.
React.js TypeScript Conditional Props - Props that depend on other Props
This video by Bruno Antunes demonstrates how to implement several conditional prop patterns in a React and TypeScript context. We'll start with the first pattern he introduces.
Watch from 01:18 to 02:08. The example shows how to create props for a panel that can be collapsed or expanded, but not both. Pay attention to how a union type (|) is combined with never to create this mutual exclusion.
Let's break down the pattern shown in the video. To create mutually exclusive propA and propB:
type BaseProps = {
// ... common props
};
// Case 1: Only propA is allowed
type PropA_Variant = BaseProps & {
propA: string;
propB?: never; // Explicitly forbid propB
};
// Case 2: Only propB is allowed
type PropB_Variant = BaseProps & {
propB: number;
propA?: never; // Explicitly forbid propA
};
// The final props type is a union of the two exclusive cases
export type MyComponentProps = PropA_Variant | PropB_Variant;
// Usage:
// <MyComponent propA="hello" /> // OK
// <MyComponent propB={123} /> // OK
// <MyComponent propA="a" propB={1} /> // Error!
By setting the alternative prop's type to never, we are telling TypeScript that it cannot have a value, thus enforcing the mutual exclusivity at compile time.
3. Pattern 2: Conditionally Required Props
Another frequent scenario is making a prop required only when another specific prop is present. For example, if a Panel is collapsible, it should also require an onToggle function.
React.js TypeScript Conditional Props - Props that depend on other Props
Let's continue with the same video to see how this second pattern is implemented.
Watch from 13:41 to 18:07. This segment demonstrates how to make a defaultCollapsed prop required only when the collapsible prop is passed. Notice again the use of a union type to define two distinct scenarios: one where collapsible is absent, and one where it is present and brings its dependent props with it.
The pattern here is similar: we define two distinct "shapes" for our props and union them together.
// Scenario 1: The component is not collapsible
type NonCollapsibleProps = {
collapsible?: never;
defaultCollapsed?: never;
// ... other props
};
// Scenario 2: The component is collapsible
type CollapsibleProps = {
collapsible: true; // This prop's presence triggers the requirement
defaultCollapsed: boolean; // This prop is now required
// ... other props
};
// The final props type
export type PanelProps = NonCollapsibleProps | CollapsibleProps;
// Usage:
// <Panel /> // OK
// <Panel collapsible={true} /> // Error: defaultCollapsed is missing
// <Panel defaultCollapsed={false} /> // Error: collapsible is missing
// <Panel collapsible={true} defaultCollapsed={false} /> // OK
Test your understanding!
Let's design the props for a flexible Button component. The button can be rendered as a standard HTML <button> or as an anchor <a> tag.
- If it's a button, it must have an
onClickhandler. - If it's a link, it must have an
hrefstring. - It cannot have both
onClickandhref.
How would you define the ButtonProps type to enforce this?
Show answer
You would define two separate types and union them:
import type { MouseEventHandler } from 'react';
// Common props for both variants
type BaseProps = {
children: React.ReactNode;
style?: React.CSSProperties;
};
// Variant 1: A standard button
type ButtonAsButton = BaseProps & {
as?: 'button';
onClick: MouseEventHandler<HTMLButtonElement>;
href?: never;
};
// Variant 2: An anchor link
type ButtonAsLink = BaseProps & {
as: 'a';
href: string;
onClick?: never;
};
export type ButtonProps = ButtonAsButton | ButtonAsLink;
// This structure now gives you compile-time safety:
// <Button as="button" onClick={() => {}}>Click</Button> // OK
// <Button as="a" href="/home">Home</Button> // OK
// <Button as="button" href="/home">Error</Button> // Error! href is not allowed
// <Button as="a" onClick={() => {}}>Error</Button> // Error! onClick is not allowed
4. Advanced Pattern: Truly Dynamic Polymorphic Props
Now we get to the most powerful use case: creating types that dynamically adapt based on generic inputs. This is where conditional types truly shine, allowing us to build extremely flexible and intelligent component APIs.
The classic example is a Dropdown component that can accept an array of simple values (like strings or numbers) or an array of complex objects.
- If it receives
string[], no other props are needed. - If it receives
T[](an array of objects), we must also providelabelPropandvalueProp, and these props must be valid keys of the object typeT.
This requires a combination of generics, conditional types, and the keyof operator.
React.js TypeScript Conditional Props - Props that depend on other Props
The final example in the Bruno Antunes video is a masterclass in this advanced technique. It combines everything we've discussed into one powerful, dynamic prop type.
Watch from 18:07 to 25:58. This is the most complex part of the lesson, so feel free to pause and re-watch. Focus on these key TypeScript features: Generics (<T>): How a generic type T is introduced to represent the items in the data array. Conditional Type: The core logic T extends number | string ? ... : ... that switches the prop definition based on whether T is a primitive or an object. keyof Operator: How keyof T is used to constrain the labelProp and valueProp to be actual keys of the objects in the data array, providing amazing autocompletion and type safety.
The final type from the video is a work of art. It's worth re-examining:
type DropdownProps<T> = {
data: T[];
} & (T extends number | string // This is the conditional check
? { // True branch: data is string[] or number[]
labelProp?: never;
valueProp?: never;
}
: { // False branch: data is an array of objects
labelProp: keyof T;
valueProp: keyof T;
}
);
This single type definition ensures that your Dropdown component is used correctly across multiple data structures, all checked at compile time.
5. Case Study: A Type-Safe Polymorphic Element Component
Let's apply these concepts to build the ultimate polymorphic component—an <Element> component that can render as any HTML tag, but with props that are type-safe for that specific tag. For example, <Element as="a" href="..."> should be valid, but <Element as="div" href="..."> should be an error. Furthermore, <Element as="hr" /> should be valid, but <Element as="hr">some children</Element> should be an error because <hr> is a void element.
This is a professional-grade pattern used in many popular UI libraries.
TypeScript/React Component Interfaces Overloading by Props
This article from FullStack.com provides a step-by-step guide to building this exact component. It introduces a few more advanced TypeScript concepts that are crucial for getting this right.
Read through the sections that build up the solution. Don't worry about memorizing all the code, but focus on understanding these key building blocks: VoidElement type: A simple union of strings representing HTML tags that cannot have children. OmitChildrenFromVoid type: A conditional type that checks if a given component type C is a VoidElement and, if so, returns its props without the children property. DistributiveOmit: This is a key insight. The standard Omit utility type doesn't distribute over unions correctly. The article shows how to create a DistributiveOmit using the T extends any ? ... : never pattern to force the Omit to apply to each member of a union individually. The TypeScript docs also cover this concept under 'Distributive Conditional Types'. OverloadedElement interface: See how it all comes together with generics to create a function interface that correctly types the component based on the as prop.
The patterns in that article, particularly DistributiveOmit, are what separate good TypeScript code from great TypeScript code. They demonstrate a deep understanding of how the type system works and allow you to build robust, bug-free abstractions.
Conclusion
You've now reached the pinnacle of component and type patterns in this course. By mastering conditional types, you can create component APIs that are not just powerful and flexible but also a joy to use, thanks to the compile-time safety and autocompletion they provide.
Key Takeaways:
- Conditional Types (
T extends U ? X : Y) allow you to embedif/elselogic directly into your type definitions. - You can enforce mutually exclusive props by creating a union of types where each type uses
neverto forbid the props of the other variants. - You can create conditionally required props by defining a union of a base case (where the prop is absent) and an enhanced case (where its presence makes other props required).
- By combining conditional types with generics,
keyof, andinfer, you can build truly dynamic and polymorphic components whose prop types adapt to the data they are given. - Advanced patterns like distributive conditional types are necessary to correctly handle union types, enabling the creation of production-grade, reusable component libraries.
Preview of the Next Lesson:
We have now concluded our deep dive into building advanced, reusable, and type-safe components. In our next and final module, we will shift our focus from building to verifying and deploying. The first lesson will be "Set up a testing environment with Vitest and React Testing Library," where you'll learn how to write robust tests to ensure your beautifully crafted components work exactly as you expect.