Creating Typed Context with createContext<T>
You'll learn: How to use TypeScript's generic parameter with createContext to define the exact shape of your context value, eliminating "any" types and catching errors at compile time.
The Generic Parameter Solution
Without TypeScript, createContext accepts any value and provides no type safety for consumers. With TypeScript, you pass a generic type parameter that describes what your context holds:
interface ThemeContextValue {
theme: 'light' | 'dark';
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
The <ThemeContextValue | undefined> tells TypeScript: "This context will eventually hold a ThemeContextValue object, but starts as undefined."
Why Start with undefined?
You typically create the context at the module level, before any component provides a real value. Using undefined as the initial value is honest—there's no theme data yet. The union type ThemeContextValue | undefined forces consumers to handle the case where the context hasn't been provided:
const value = useContext(ThemeContext);
// value is ThemeContextValue | undefined
if (!value) {
throw new Error('useTheme must be used within ThemeProvider');
}
// Now value is ThemeContextValue
This pattern catches mistakes where someone uses useContext(ThemeContext) outside the provider tree.
Alternative: Non-Null Default
If you provide a sensible default immediately, you can avoid the union:
const ThemeContext = createContext<ThemeContextValue>({
theme: 'light',
toggleTheme: () => {},
});
Now consumers get ThemeContextValue directly, but you lose the safety check for missing providers.
Key Takeaway: Use createContext<YourType>() with a generic parameter to make your context type-safe—TypeScript will verify every provider value and consumer usage matches your defined shape.