Type-Safe Slots with TypeScript
What you'll learn: How to use TypeScript to ensure only valid content goes into your component slots.
Why Type Safety Matters for Slots
When you accept JSX content through props (slots), TypeScript can help catch mistakes before runtime. Without types, someone could accidentally pass a number when you expect a button, or pass nothing when a slot is required. Type safety makes your slot API predictable and prevents bugs.
Defining Slot Types
The most flexible slot type is ReactNode, which accepts any renderable content:
import { ReactNode } from 'react';
interface LayoutProps {
header: ReactNode;
sidebar: ReactNode;
content: ReactNode;
footer?: ReactNode; // Optional slot
}
function Layout({ header, sidebar, content, footer }: LayoutProps) {
return (
<div>
<header>{header}</header>
<aside>{sidebar}</aside>
<main>{content}</main>
{footer && <footer>{footer}</footer>}
</div>
);
}
More Specific Types
Sometimes you want stricter control. Use ReactElement for actual elements, or specific element types:
import { ReactElement } from 'react';
interface CardProps {
title: string | ReactElement; // String or element only
actions: ReactElement<{ onClick: () => void }>; // Must have onClick
}
You can even require specific components:
interface DialogProps {
trigger: ReactElement<typeof Button>; // Must be a Button
}
The Trade-off
ReactNode is permissive (accepts strings, numbers, elements). Stricter types catch more errors but limit flexibility. Choose based on whether you need control or freedom.
Key Takeaway: Use ReactNode for flexible slots, ReactElement when you need actual components, and specific types when you want to enforce exactly what content is allowed—TypeScript makes your slot contracts explicit and compiler-verified.