Course contentsShow
← React
Lesson 1949 of 2,39644. Styling ApproachesFree lesson

TypeScript and Design Token Consistency

Keep CSS variable names and JavaScript theme objects in sync using TypeScript and code generation strategies.

TypeScript and Design Token Consistency

What you'll learn: How to use TypeScript to ensure your CSS variable names and JavaScript theme objects stay perfectly in sync.

The Problem of Drift

When you define CSS variables like --color-primary and reference them in JavaScript theme objects, they can easily fall out of sync. You might rename a CSS variable but forget to update the JavaScript side—or vice versa. This breaks at runtime, often in subtle ways.

The solution: Use TypeScript to create a single source of truth that generates both your CSS variables and your type-safe JavaScript constants.

The Pattern

Define your design tokens once in TypeScript:

const designTokens = {
  colors: {
    primary: '#3b82f6',
    secondary: '#8b5cf6',
  },
  spacing: {
    sm: '0.5rem',
    md: '1rem',
  }
} as const;

type DesignTokens = typeof designTokens;

Generate CSS variables from this object:

export function getCSSVariables(): string {
  return `
    --color-primary: ${designTokens.colors.primary};
    --color-secondary: ${designTokens.colors.secondary};
    --spacing-sm: ${designTokens.spacing.sm};
    --spacing-md: ${designTokens.spacing.md};
  `;
}

Export typed accessors for JavaScript:

export const theme: DesignTokens = designTokens;

Now TypeScript autocomplete works for theme.colors.primary, and if you rename a token, TypeScript errors guide you to update all references. Your CSS variables are generated from the same source, eliminating drift.

Key Takeaway: Using TypeScript and code generation to maintain a single source of truth for design tokens prevents CSS variable and JavaScript theme object drift, catching mismatches at compile-time instead of runtime.