TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引“User_Economy”类型

KristalkillPlay

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

错误: 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));

如何解决这个问题?

j1mbl3s

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 / falsey值。回调为其返回真值的第一个元素将是由 返回的元素find()在这种情况下没有理由对typed.toLowerCase() === x ? x : null. 只需使用typed.toLowerCase() === x.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章