Skip to content

Instantly share code, notes, and snippets.

@luistak
Created September 22, 2020 12:21
Show Gist options
  • Save luistak/2a72940d528518e9a33c27af47158f7c to your computer and use it in GitHub Desktop.
Save luistak/2a72940d528518e9a33c27af47158f7c to your computer and use it in GitHub Desktop.
type ThemedCss = FlattenInterpolation<ThemeProps<DefaultTheme>>;
type VariantOptions<T extends string> = {
variant: T | undefined;
variants: Record<T, ThemedCss>;
defaultStyle: ThemedCss;
};
type VariantCallback<T, K extends string> = (props: T) => VariantOptions<K>;
function pickVariantStyleV2<T, K extends string>(
fn: VariantCallback<T, K>
): (props: T) => ThemedCss {
return function themedVariant(props: T): ThemedCss {
const { variant, variants, defaultStyle } = fn(props);
if (!variant) {
return defaultStyle;
}
return variants[variant] || defaultStyle;
};
}
@luistak
Copy link
Author

luistak commented Sep 22, 2020

Example usage:

const Medium = css`
  font-size: 24px;
`;

const Small = css`
  font-size: 16px;
`;

const ExtraSmall = css`
  font-size: 8px;
`;

const AwesomeComponent = styled.div`
  ${pickVariantStyle<AwesomeComponentProps, VariantsType>((props: AwesomeComponentProps) => ({
    variant: props?.size,
    variants: {
      m: Medium,
      s: Small,
      xs: ExtraSmall,
    },
    defaultStyle: Medium,
  }))}
`;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment