Skip to main content

Automatic Inference

When you define variants, TypeScript infers the types automatically.
✅ No as const needed. No manual type definitions.

How It Works

better-styled uses const type parameters to preserve literal types:
The const modifier tells TypeScript to infer exact literal types ("sm" | "md" | "lg") instead of widening to string.

Context Type Inference

createStyledContext also uses const type parameters:
The special ["boolean"] array is transformed into a proper boolean type, not "boolean".

Getting Variant Props Type

Sometimes you need the variant props type for other purposes. Use TypeScript’s inference:

Shared Configs

When multiple components share the same variants and context, use styledConfig() to create a single typed config:
styledConfig() uses the same type inference as styled() — no generics needed. TypeScript validates that the config is compatible with both components simultaneously.
styledConfig() is an identity function — it returns the config unchanged. It exists purely for type inference, with zero runtime cost.

Extending Components

When you wrap a styled component, types flow through:

Strict Variants

By default, variant props are optional. If you want to require them, don’t use defaultVariants:

Working with Refs

Refs work as expected. The component forwards refs to the underlying element:
For React Native:

Generic Components

If you need a component that works with multiple element types:

Common Patterns

Omit Specific Variants

Require Children

Tips

Don’t add type annotations unless necessary. The inference is designed to work without them.
Always pass arrays directly to createStyledContext. Don’t assign them to variables first, or you’ll lose the literal types.
Hover over components in your IDE to see the inferred types. This is the best way to understand what TypeScript sees.

API Reference

Complete API documentation