首页 > 解决方案 > 样式化的组件抛出奇怪的打字稿错误

问题描述

我在我的 RN 项目中设置了组件和打字稿的样式

Typescript 在我的一个文件中抛出了一个奇怪的错误,它说Element implicitly has 'any' type because expression of type 'string' can't be used to index 'ColorKeyType'

受影响的代码,错误在return theme.colors[color]部分

const StyledText = styled(Text)<TextStyleProps>`
  color: ${({ color, theme }) => {
    if (color) {
      return theme.colors[color] || color;
    }
    return theme.colors.text;
  }}
`;

我的主题颜色键入如下:

interface ColorKeyType {
  primary: string;
  ... more colors like the one above
}

然后我使用如下类型:

{
    colors: ColorKeyType;
    fonts: {
      families: {
        primary: { [key in FontFamilyType]: string };
      };
      fontSize: { [key in FontSizeType]: number };
      letterSpacing: number;
    };
}

提前感谢任何可能的解决方案!

标签: reactjstypescriptreact-nativestyled-components

解决方案


将您的颜色类型更改为keyof ColorKeyType

interface TextStyleProps {
  ...
  color: keyof ColorKeyType;
}

推荐阅读