首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型“未定义”不能用作索引类型

问类型“未定义”不能用作索引类型
EN

Stack Overflow用户
提问于 2021-03-04 14:39:43
回答 1查看 2.5K关注 0票数 0

我在尝试将Map的值动态地传递到主题支柱时会出错。我做错了什么?

ps:不能加"!“埃林特原因

代码语言:javascript
复制
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};
    `}  
`;

当将颜色传递给背景颜色中的主题时,我会得到错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-04 14:47:43

不幸的是,您不能强迫Map具有非定义的返回类型.因此,您需要用一个简单的对象替换它,并为它分配一个Record类型。

此外,我建议您创建一个类型联合ColorMapKeys,在这里您应该定义所有可能的键。

代码语言:javascript
复制
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};
    `}  
`;

现在一切都会好的

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66477262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档