You may encounter an undefined condition when using an enum to index optional properties
P粉653045807
P粉653045807 2023-09-10 14:07:23
0
1
441

I'm trying to implement an optional style override for my style component.

Currently I have this:

这是一个函数,将会将我改变的样式与主题中的默认样式合并。
const mergeComponentTheme = (mode: ThemeMode, defaultTheme: T, overridingTheme?: CustomComponentStyle): T => { return Object.keys(defaultTheme).reduce((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); };
这是我目前的使用方式。
const Button = styled.button>` ${({ theme, customStyle }) => { const componentStyle = mergeComponentTheme(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; } `; }} `;
这些是示例中使用的所有类型。
type CustomStyled = { customStyle?: CustomComponentStyle; }; type CustomComponentStyle = { light?: Partial; dark?: Partial; }; 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 cleaner way to do this. I'm open to suggestions.

However, I almost forgot the title of the question. So my main question is, if I remove this part from thethemeModeconstant as keyof typeof overridingTheme;,overridingTheme[themeMode]will say even after checking It may be undefined.

P粉653045807
P粉653045807

reply all (1)
P粉734486718

try:

const value = (overridingTheme?.[themeMode]?.[property]) ?? defaultTheme[property];
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!