Type Safety with useContext and TypeScript
What you'll learn: How to properly type your Context values so TypeScript catches errors when you consume context incorrectly.
Why Type Safety Matters with Context
When you use createContext without types, TypeScript can't help you catch mistakes like accessing non-existent properties or passing the wrong value shape to your Provider. Type safety ensures that:
- The value you provide matches the expected shape
- When you consume context with
useContext, you get proper autocomplete - TypeScript catches typos and incorrect usage at compile time
Typing createContext
You specify the context value type as a generic parameter:
interface ThemeContextValue {
theme: 'light' | 'dark';
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
Notice we use ThemeContextValue | undefined because initially, there's no Provider — the default value is undefined.
Typing useContext Calls
When consuming context, TypeScript infers the return type from your context definition:
function ThemedButton() {
const value = useContext(ThemeContext);
// value is ThemeContextValue | undefined
if (!value) {
throw new Error('ThemedButton must be used within ThemeProvider');
}
// Now TypeScript knows value is ThemeContextValue
return <button onClick={value.toggleTheme}>Toggle</button>;
}
Custom Hook Pattern for Better Types
Encapsulate the null check in a custom hook:
function useTheme(): ThemeContextValue {
const value = useContext(ThemeContext);
if (!value) {
throw new Error('useTheme must be used within ThemeProvider');
}
return value; // TypeScript knows this is never undefined
}
Now consumers get clean, non-nullable types automatically.
Key Takeaway: Type your context with createContext<YourType | undefined>(undefined) and wrap useContext in a custom hook that throws if the value is undefined — this gives you type safety without constant null checks in every component.