我遇到了一个问题,我不明白为什么会这样说。
问题:
TS7053:元素隐式地具有“ any”类型,因为类型“ string”的表达式不能用于索引类型“ typeof
”我有一个变量作为字符串。我们可以将其称为componentName。我导入了一些像这样的组件:“将*作为_icons从“ ./icons”导入;“我想邀请一个像这样的组件“ _icons [this.props.name!]”。但是我对我的警告是错误的句子
import {SvgIconNamespace} from "../namespaces";
import * as _icons from "./icons";
import {AbstractIconComponent} from "./icons";
import React from "react";
import {View} from "react-native";
export class Icon extends AbstractIconComponent<SvgIconNamespace.SvgIconPropsInterface, SvgIconNamespace.SvgIconStateInterface> {
render(): React.ReactNode {
let iconElement = React.createElement(
_icons[this.props.name!], // Error sentence in this line!
{ size: this.props.size!, fill: this.props.fill!},
)
return(
<View>
{ iconElement }
</View>
);
}
constructor(props: SvgIconNamespace.SvgIconPropsInterface) {
super(props)
}
}
props.name:字符串='PlusSquareIcon'
答案 0 :(得分:0)
Typescript期望您为图标导出指定的特定名称(例如“ PlusSquareIcon”),而不仅仅是任何string
(Icon
name
道具的类型),这是为什么会出现此错误。
如果您想像输入任何字符串一样继续键入props.name
,可以解决此问题的一种方法是将_icons
转换为如下所示的索引签名接口:
import {SvgIconNamespace} from "../namespaces";
import * as _icons from "./icons";
import {AbstractIconComponent} from "./icons";
import React from "react";
import {View} from "react-native";
interface ImportedIcons {
[key: string]: React.FC<{size: number, fill: string}>
}
export class Icon extends AbstractIconComponent<SvgIconNamespace.SvgIconPropsInterface, SvgIconNamespace.SvgIconStateInterface> {
render(): React.ReactNode {
let iconElement = React.createElement(
(_icons as ImportedIcons)[this.props.name!], // Error sentence in this line!
{ size: this.props.size!, fill: this.props.fill!},
)
return(
<View>
{ iconElement }
</View>
);
}
constructor(props: SvgIconNamespace.SvgIconPropsInterface) {
super(props)
}
}