Type-Safe Theme Contracts
You'll learn how to create type-safe theme contracts with createTheme() that give you autocomplete and type-checking for design tokens across your entire application.
The Core Idea
In vanilla-extract, a theme contract is like a blueprint that defines which design tokens exist (colors, spacing, typography) without initially specifying their values. Once you establish this contract, TypeScript knows exactly what tokens are available, giving you compile-time safety when styling components.
Think of it like a menu template for a restaurant chain: the contract lists all possible items (appetizers, entrees, desserts), but each location can fill in different actual dishes. Your IDE will warn you if you try to order something not on the menu.
Creating a Theme Contract
import { createTheme, createThemeContract } from '@vanilla-extract/css';
// Define the structure (the contract)
export const vars = createThemeContract({
color: {
primary: null,
background: null,
text: null
},
spacing: {
small: null,
medium: null,
large: null
}
});
// Implement the contract (assign actual values)
export const lightTheme = createTheme(vars, {
color: {
primary: '#007bff',
background: '#ffffff',
text: '#000000'
},
spacing: {
small: '8px',
medium: '16px',
large: '24px'
}
});
Now when you use vars.color.primary in your styles, TypeScript knows this property exists. Typo vars.color.primaryy? Instant error. Try to add vars.color.secondary without updating the contract? Type error.
This makes refactoring themes safe and IDE autocomplete incredibly helpful when styling.
Key Takeaway: Theme contracts establish a type-safe structure for design tokens, ensuring you can't reference non-existent values and enabling autocomplete throughout your styling code.