javascript - TypeScript - 元素隐式具有“任何”类型 [...] 在类型上找不到具有“字符串”类型参数的索引签名
问题描述
我正在努力克服 TS 上的错误。
我根据我创建的 2 个接口(WalletInformationsEdit 和 UserInformationsEdit)定义值(在代码下方)
我遇到的问题是在 DB 查询之后的那一行,value[field]下划线表示:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'WalletInformationsEdit | UserInformationsEdit'.
No index signature with a parameter of type 'string' was found on type 'WalletInformationsEdit | UserInformationsEdit'.
我找到了 2 个解决方案来避免此错误消息,但我不好,因为它们使我的代码受到的保护较少:
1/ 在 TS 配置中,如果我取消 "strict": true 和 "noImplicitAny": true -> working
2/如果我用“任何”类型定义值,-> 工作
但我想两者都不值得。
你对处理这个案子有什么建议吗?
提前致谢,
保罗
public async update(value: WalletInformationsEdit | UserInformationsEdit): Promise<any> {
try {
// saving id before elem treatment
const keepId = value.id
delete value.id
let filterFields = []
for (let elem of Object.keys(value)) {
filterFields.push(elem)
}
let i = 0;
let updateList = [];
for (const field of filterFields) {
updateList.push(`"${field}" = $${++i}`);
}
const preparedQuery = {
text: `UPDATE "${this.constructor.name.toLowerCase()}" SET
${updateList.join()}
WHERE id = $${++i}
RETURNING *
`,
values: [...filterFields.map((field) => value[field]), keepId],
};
const result = await db.query(preparedQuery);
return result.rows[0]
} catch (error) {
throw new Error(error.message)
}
}
WalletInformationsEdit 和 UserInformationsEdit 接口
export interface UserInformationsEdit {
id?: number,
email?: string,
password?: string,
country?: string
}
export interface WalletInformationsEdit {
id?: number,
name?: string,
is_default?: boolean,
}
解决方案
我终于找到了答案,在我的情况下声明索引签名,我不得不这样声明
export interface WalletInformationsEdit {
[key: string]: number | string | boolean | undefined;
id?: number,
name?: string,
is_default?: boolean
}
[key: string] -> 索引被读取为字符串
: 号码 | 字符串 | 布尔值 | undefined -> 构成我的接口的每种类型 + undefined 因为属性是可选的
感谢@DigitalDrifter 的链接:-)
推荐阅读
- cvxpy - 目标不是 DCP。它的下列子表达式不是
- node.js - AWS Lambda | 从 S3 读取多个文件 | 创建组合 JSON | 面临性能问题
- javascript - 如何从包含日期范围的字符串中提取年份 [Typescript/Angular]
- swift - 如何在 iOS 13 上共享文本和 URL 到提醒事项
- excel - Excel 多级数组公式与部分字符串匹配以求和结果单元格
- mongodb - 基于ObjectID的Mongodb Aggregation中的查询问题
- reactjs - React 函数的返回类型是什么
- ios - 提交到 AppStore Connect 时不支持 iOS 13
- angular - Angular 8后退按钮和参数
- python - Python 访问从导入的函数返回元组