TypeScript
Extracting Variant Types
cva
offers the VariantProps
helper to extract variant types
// components/button.ts
import type { VariantProps } from "cva";
import { cva, cx } from "cva";
/**
* Button
*/
export type ButtonProps = VariantProps<typeof button>;
export const button = cva(/* … */);
Required Variants
To keep the API small and unopinionated, cva
doesn’t offer a built-in solution for setting required variants.
Instead, we recommend using TypeScript’s Utility Types:
// components/button.ts
import { cva, type VariantProps } from "cva";
export type ButtonVariantProps = VariantProps<typeof buttonVariants>;
export const buttonVariants = cva({
base: "…",
variants: {
optional: { a: "…", b: "…" },
required: { a: "…", b: "…" },
},
});
/**
* Button
*/
export interface ButtonProps
extends Omit<ButtonVariantProps, "required">,
Required<Pick<ButtonVariantProps, "required">> {}
export const button = (props: ButtonProps) => buttonVariants(props);
// ❌ TypeScript Error:
// Argument of type "{}": is not assignable to parameter of type "ButtonProps".
// Property "required" is missing in type "{}" but required in type
// "ButtonProps".
button({});
// ✅
button({ required: "a" });