【问题标题】:Styled component throws weird typescript error样式化的组件抛出奇怪的打字稿错误
【发布时间】:2021-03-13 11:55:25
【问题描述】:

我在我的 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;
    };
}

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

【问题讨论】:

    标签: reactjs typescript react-native styled-components


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 1970-01-01
      • 2019-06-19
      • 2021-06-07
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      相关资源
      最近更新 更多