我大部分时间都在这个问题上,但没有答案
错误:
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));
如何解决这个问题?
答案 0 :(得分: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()
回调通常应该返回一个布尔值,但它也接受真/假值。回调为其返回真值的第一个元素将是 find()
返回的元素。在这种情况下没有理由对 typed.toLowerCase() === x ? x : null
进行额外处理。只需使用 typed.toLowerCase() === x
。