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" - User
that is what I do already
but 'variantClass' is still of type string
- Assistant
I see. To make the
variantClassvariable type-safe within the function, you can use a type predicate to narrow down the type ofvariantClass. Here's an updated version of the function:typescript - User
ok what if I don't want to force type with type casting (wich is a bad practice)
- Assistant
If you don't want to force the type of
variantClasswith a type cast, you can use theas constassertion to make the type literal readonly. Here's an updated version of the code:typescript
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.