Importing types
You can import all types at once:
import type * as Classed from "@tw-classed/react";
These include:
Classed.ClassedComponentType
- the type of a classed componentClassed.InferVariantProps
Infers the variant props of a set of variants (internal but exported for convenience)Classed.VariantProps
Infers the variant props of a componentClassed.Variants
The legal variants of a component (use to type an external variant object)
Extract variants from a component
import type * as Classed from "@tw-classed/react";
const Button = classed("button", "px-2 py-1", {
variants: {
color: {
blue: "bg-blue-500",
red: "bg-red-500",
},
},
});
type ButtonVariants = Classed.VariantProps<typeof Button>;
// {
// color: "blue" | "red";
// }
export type ButtonProps = React.ComponentProps<typeof Button>; // This of course works as expected
Typescript 4.9 and above (satisfies api)
On Typescript 4.9 and above you can use the satisfies keyword to define a variant object outside of the classed
function. This is useful when creating shared variants.
import { Variants, classed } from "@tw-classed/react";
const colorVariants = {
color: {
blue: "bg-blue-500",
red: "bg-red-500",
},
} satisfies Variants;
// In Button.tsx
const Button = classed("button", "px-2 py-1", {
variants: colorVariants,
});
type ButtonVariants = Classed.VariantProps<typeof Button>; // Variants are persisted.