- 已编辑
在尝试用 TypeScript 写 node 服务,有一段插入数据库的代码如下:
interface DBRecord {
id: number;
title: string;
url: string;
guid: string;
};
/**
* 往 DB 中插入新条目,返回新增行数
* @param itemsList 需插入的条目
*/
export async function insertItems(itemsList: DBRecord[]) {
const result = await Promise.all(
itemsList.map((item) => {
const sql = `INSERT INTO "records" ("id", "title", "url", "guid") VALUES (?, ?, ?, ?);`;
return DB.run(
sql,
["id", "title", "url", "guid"].map((key) => item[key])
);
})
);
return result.reduce((accu, curr) => accu + curr.changes, 0);
}
编译时出现了以下的报错:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'DBRecord'.
No index signature with a parameter of type 'string' was found on type 'DBRecord'.ts(7053)
在 reddit 找到一个类似的问题:
https://www.reddit.com/r/typescript/comments/edzgtw/help_no_index_signature_with_a_parameter_of_type/
It's because key has type string, but the single object in temp only accepts values of type "object" | "object2" as keys.
对应到我这里的上下文,大概意思是:key 是 string 的类型,但我的 item 访问属性时候只接受 "id" | "title" | "url" | "guid"
,然后类型不对应。
该如何解决这个报错呢?