variant: "button-brand" "button-primary" "button-primary-inverse" "button-secondary"…
Private research annotation
Sign in to add a private research label or note.
- User
variant: "button-brand" | "button-primary" | "button-primary-inverse" | "button-secondary" | "button-tertiary" | "button-ghost" | "underlined" | "unstyled"
codeconst variantClass = variant.replace('button-' as const, '' as const);variantClass is of type string, how can it be typesafe ?
- Assistant
To make the
variantClasstype safe, you can use TypeScript's conditional types and theinferkeyword to extract the part of the string after "button-". Here's how you can modify your code to achieve this:typescripttype ButtonVariants = "button-brand" | "button-primary" | "button-primary-inverse" | "button-secondary" | "button-tertiary" | "button-ghost" | "underlined" | "unstyled"; type ExtractVariantClass<T extends ButtonVariants> = T extends `button-${infer U}` ? U : never; function getVariantClass<T extends ButtonVariants>(variant: T): ExtractVariantClass<T> { const variantClass = variant.replace('button-' as const, '' as const) as ExtractVariantClass<T>; return variantClass; } // Usage example: const buttonVariant: ButtonVariants = "button-primary"; const variantClass = getVariantClass(buttonVariant); // variantClass is of type "primary"
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.