我在尝试将Map的值动态地传递到主题支柱时会出错。我做错了什么?
ps:不能加"!“埃林特原因
interface ColorsInterface {
bgColor: keyof ThemeVars['colors'];
textColor: keyof ThemeVars['colors'];
}
const colorMap = new Map<string, ColorsInterface>([
['standard', { bgColor: 'primaryNormal', textColor: 'white' }],
['accent', { bgColor: 'accentNormal', textColor: 'white' }],
['neutral', { bgColor: 'grayExtraDark', textColor: 'white' }],
['flat', { bgColor: 'white', textColor: 'primaryNormal' }],
['text', { bgColor: 'white', textColor: 'grayExtraDark' }],
['disabled', { bgColor: 'grayLight', textColor: 'grayDark' }],
]);
export const ButtonWrapper = styled.button<ButtonInterface>`
${props =>
props.buttonType &&
css`
background-color: ${props.theme.colors[colorMap.get(props.buttonType).bgColor]};
color: ${colorMap.get(props.buttonType)?.textColor};
`}
`;当将颜色传递给背景颜色中的主题时,我会得到错误。
发布于 2021-03-04 14:47:43
不幸的是,您不能强迫Map具有非定义的返回类型.因此,您需要用一个简单的对象替换它,并为它分配一个Record类型。
此外,我建议您创建一个类型联合ColorMapKeys,在这里您应该定义所有可能的键。
type ColorMapKeys = 'standard' | 'accent' | 'neutral' | 'flat' | 'text' | 'disabled';
type ColorMap = Record<ColorMapKeys, ColorsInterface>;
const colorMap: ColorMap = {
'standard': { bgColor: 'primaryNormal', textColor: 'white' },
'accent': { bgColor: 'accentNormal', textColor: 'white' },
'neutral': { bgColor: 'grayExtraDark', textColor: 'white' },
'flat': { bgColor: 'white', textColor: 'primaryNormal' },
'text': { bgColor: 'white', textColor: 'grayExtraDark' },
'disabled': { bgColor: 'grayLight', textColor: 'grayDark' },
};
export const ButtonWrapper = styled.button<ButtonInterface>`
${(props: Props) =>
props.buttonType &&
css`
background-color: ${props.theme.colors[colorMap[props.buttonType].bgColor]};
color: ${colorMap[props.buttonType].textColor};
`}
`;现在一切都会好的
https://stackoverflow.com/questions/66477262
复制相似问题