【问题标题】:TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User_Economy'TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“用户经济”
【发布时间】:2021-08-28 23:59:39
【问题描述】:

我大部分时间都花在这个问题上,但没有答案

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


    interface User_Economy {
        rep: number
        money: number
        level: number
        xp: number
        box: number[]
    }
    interface User_Interface{
        Economy: User_Economy
    }
    data = await this.client.db.insert_one<User_Interface>('users', User_basic(member.id, message.guild.id));
    const type: keyof {[key: string]: User_Economy} = ['level', 'money', 'rep', 'xp'].find(x => {
                return typed.toLowerCase() === x ? x : null
            })
    data.Economy[type] += Math.floor(parseInt(amount));

如何解决这个问题?

【问题讨论】:

    标签: javascript node.js typescript object types


    【解决方案1】:

    您现在定义的const type 的类型是string。 正如错误所暗示的那样,User_Economy 接口没有带有“字符串”类型参数的索引签名,即类似于:

    interface User_Economy {
      [key: string]: unknown;
    }
    

    您希望在最后一行中使用的const type,而不是keyof {[key: string]: User_Economy}(相当于string)应该是keyof User_Economy,即User_Economy 的单数预定义键,在为了引用当前定义的 User_Economy 键。

    提供的代码还有其他问题,例如User_Economy.box 属性不能由+= 运算符分配。您可能希望使用Exclude 实用程序类型将其从结果中排除。另一个问题是Array.prototype.find() 方法可以返回undefined,在分配data.Economy[type] 之前必须考虑这一点。

    例如,下面是一些总是将1 添加到data.Economy.level 的代码,导致其值被设置为2

    interface User_Economy {
      rep: number;
      money: number;
      level: number;
      xp: number;
      box: number[];
    }
    interface User_Interface{
      Economy: User_Economy;
    }
    type KUEExcludingBox = Exclude<keyof User_Economy, 'box'>;
    
    const data: User_Interface = {
      Economy: {
        rep: 1,
        money: 1,
        level: 1,
        xp: 1,
        box: [],
      },
    };
    
    const key: KUEExcludingBox | undefined = (['level', 'money', 'rep', 'xp'] as KUEExcludingBox[])
      .find(x => 'level' === x);
    if (key !== undefined) {
      data.Economy[key] += Math.floor(parseInt('1'));
    }
    
    console.log(data);
    

    TypeScript Playground上查看。

    旁白
    • 您应该避免使用像type 这样的关键字作为变量名。
    • Array.prototype.find() 回调通常应该返回一个布尔值,尽管它也接受真/假值。回调返回truthy 的第一个元素将是find() 返回的元素。在这种情况下,没有理由对typed.toLowerCase() === x ? x : null 进行额外处理。只需使用typed.toLowerCase() === x

    【讨论】:

    • 谢谢,我不知道 Exclude )))
    猜你喜欢
    • 2021-08-08
    • 1970-01-01
    • 2021-03-17
    • 2021-04-20
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2020-11-13
    • 2019-12-17
    相关资源
    最近更新 更多