【发布时间】: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