TypeScript trick you might not know đź‘€
Ever wanted to suggest specific values for a prop while still allowing any custom string?
You can get the best of both worlds: autocomplete without restricting flexibility.
Your IDE suggests the predefined values, but TypeScript still accepts custom ones.
No more choosing between strict unions and plain
tsx
type AutoComplete<T extends string> = T | Omit<string, T>; type ButtonVariant = AutoComplete< "primary" | "secondary" | "ghost" >; interface ButtonProps { variant: ButtonVariant; } const Button = ({ variant }: ButtonProps) => ( <button className={`btn--${variant}`}> Click me </button> ); // Autocomplete suggestions âś… <Button variant="primary" /> <Button variant="secondary" /> // Custom values also work âś… <Button variant="my-custom-variant" />
string.commit 2e48661