Search code examples
reactjstypescriptstyled-components

Possibly undefined when indexing optional properties with enum


I am trying to implement a optional style overriding for my styled components.

Currently what I have is this:

This is a function that will be merging my changed style to the default one from the theme.
const mergeComponentTheme = <T extends object>(mode: ThemeMode, defaultTheme: T, overridingTheme?: CustomComponentStyle<T>): T => {
  return Object.keys(defaultTheme).reduce<T>((previousValue, currentValue) => {
    const property = currentValue as keyof T;
    const themeMode = mode as keyof typeof overridingTheme;
    const value = (overridingTheme && overridingTheme[themeMode][property]) || defaultTheme[property];

    return { ...previousValue, [currentValue]: value };
  }, {} as T);
};
This is how I am using it right now.
const Button = styled.button<CustomStyled<ButtonTheme>>`
  ${({ theme, customStyle }) => {
    const componentStyle = mergeComponentTheme<ButtonTheme>(theme.mode, theme.current.button, customStyle);

    return css`
      background-color: ${componentStyle.backgroundColor};
      color: ${componentStyle.foregroundColor};
      padding: ${componentStyle.padding};
      margin: ${componentStyle.margin};
      border-radius: ${componentStyle.borderRadius};
      filter: drop-shadow(0 0 2px ${componentStyle.dropShadowColor});
      transition: all 0.2s ease-in-out;

      &:hover {
        background-color: ${componentStyle.backgroundColorHover};
        cursor: pointer;
      }
    `;
  }}
`;
These are all the types used in the example.
type CustomStyled<T> = {
  customStyle?: CustomComponentStyle<T>;
};

type CustomComponentStyle<T> = {
  light?: Partial<T>;
  dark?: Partial<T>;
};

enum ThemeMode {
  LIGHT = 'light',
  DARK = 'dark',
}

interface ButtonTheme extends GenericTheme {
  borderRadius: Radius;
}

type GenericTheme = {
  backgroundColor: Color;
  foregroundColor: Color;
  backgroundColorHover: Color;
  foregroundColorHover: Color;
  dropShadowColor: Color;
  margin: Space;
  padding: Space;
};

Is there a neater way of doing this. I am open for suggestions.

The question title though, almost forgot it. So my main problem is that if I remove this part as keyof typeof overridingTheme; from the themeMode constant overridingTheme[themeMode] says it can be possibly undefined even after checking for it.


Solution

  • Try:

    const value = (overridingTheme?.[themeMode]?.[property]) ?? defaultTheme[property];