【问题标题】:Element implicitly has an 'any' type because expression of type 'string' can't be used to index type A元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型 A
【发布时间】:2020-10-29 07:44:03
【问题描述】:

问题中的类型A是指在这个例子中BadgeTypes类型 完全错误是

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type A.No index signature with a parameter of type 'string' was found on type A

沙盒链接: https://codesandbox.io/s/typescript-type-checking-question-hkfmc (注意:但由于某种原因它没有显示错误-_-)

我遇到了问题,请找到适当的解决方案。所有相关的帖子都在我头上。不胜感激,并附上解释

type BadgeTypes = {
  success: string;
  secondary: string;
  alert: string;
  text: string;
};

type Theme = {
  fonts?: object;
  borderRadius?: string;
  primary?: object;
  accent?: object;
  action?: object;
  stories?: object;
  checkbox?: object;
  badge: BadgeTypes;
  button?: object;
  page?: object;
  states?: object;
  modal?: object;
};
interface Props {
  theme: Theme;
  large: boolean;
  type: keyof BadgeTypes;
}
const StyledBadge = styled.span<Props>`
  display: inline-block;
  border-radius: ${(props: Props) => props.theme.borderRadius};
  text-align: center;
  color: ${(props: Props) => props.theme.badge.text};
  font-size: ${(props: Props) => (props.large ? `1.4rem` : `1rem`)};
  padding: ${(props: Props) =>
    props.large ? `0 .8rem` : `0.2rem 0.6rem 0.3rem 0.6rem`};

  // error happens here
  background: ${(props: Props) => props.theme.badge[`${props.type}`]};
`;

【问题讨论】:

  • 请发布实际代码文本而不是图像,如How to Ask 中所述。理想情况下,此类代码还应该构成一个minimal reproducible example,可以将其放入像The TypeScript Playground 这样的独立IDE 以演示您的问题。您越容易让其他人自己测试问题,您获得有用答案的机会就越大。祝你好运!

标签: javascript typescript


【解决方案1】:

问题是使用template string 来索引badge

基本上:

// this is a string
let x = `${props.type}`;

// this is "success" | "secondary" | "alert" | "text"
let y = props.type;

如果你写props.theme.badge[props.type],类型检查器应该很高兴。

【讨论】:

  • WOOOOOOOOOOOOWWWWW!大声笑从没想过!谢谢
  • 简单的东西总是最容易错过的:)
猜你喜欢
  • 2021-03-17
  • 2021-04-20
  • 1970-01-01
  • 2020-11-13
  • 2019-12-17
  • 2020-10-04
  • 2019-12-15
  • 1970-01-01
  • 2021-09-22
相关资源
最近更新 更多