【问题标题】:Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“typeof”
【发布时间】:2020-11-14 15:12:17
【问题描述】:

我有一个问题,我不明白它为什么这么说。

问题:

TS7053:元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“typeof”

我有一个变量作为字符串。我们可以称它为componentName。我导入了一些这样的组件:“import * as _icons from "./icons";”我想邀请一个像“_icons[this.props.name!]”这样的组件。但是我的ide警告我作为错误句

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: string = 'PlusSquareIcon'

【问题讨论】:

    标签: reactjs typescript types native


    【解决方案1】:

    Typescript 期待您为图标导出提供的特定名称(例如“PlusSquareIcon”),而不仅仅是任何 stringIcon 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)
            }
    
        }
    
    

    【讨论】:

    • 我ide说应该是这样的。 '(_icons as unknown as ImportedIcons)[this.props.name!],'
    • 您能在问题中分享您的icons 文件吗?可能有更好的输入方式。
    猜你喜欢
    • 2022-11-10
    • 2022-01-17
    • 2021-12-24
    • 2022-10-08
    • 2019-11-24
    • 2023-01-09
    • 2021-10-24
    • 1970-01-01
    • 2022-08-17
    相关资源
    最近更新 更多