为什么 TypeScript 会抛出错误:TS2339:类型“EventTarget”上不存在属性“错误”

puw*_*eac 1 indexeddb typescript angular

我尝试用 IndexedDB 为一家小书店编写一个有角度的应用程序。\n我将索引“isbn”设置为唯一,现在我尝试引发错误,因为我想告诉用户 isbn 必须是唯一的并想显示错误消息。

\n\n

我可以console.log(e)并获得以下输出:

\n\n

事件

\n\n
   {isTrusted: true, type: "error", \n   target: IDBRequest, currentTarget: IDBRequest, eventPhase: 2, \xe2\x80\xa6}\n\nisTrusted: true\ntype: "error"\ntarget: IDBRequest\nresult: undefined\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

错误:DOMException:无法将键添加到索引“isbn”:至少有一个键不满足唯一性要求。

\n
\n\n

问题:

\n\n

我无法编写console.log(e.target.error)因为 TypeScript 说:\nTS2339: 类型 \'EventTarget\' 上不存在属性 \'error\'

\n\n

为什么?

\n\n#\n\n

这是方法:

\n\n

新增项目() {

\n\n
const request = window.indexedDB.open(this.database.name);\n\nrequest.onsuccess = event => {\n\n  const item = {\n    title: \'\',\n    isbn: 1,\n    descrition: \'\',\n    rating:  1\n  };\n\n  const transaction = request.result.transaction([\'books\'], \'readwrite\');\n  const objectStore = transaction.objectStore(\'books\');\n  const objectStoreRequest = objectStore.add(item);\n\n  objectStoreRequest.onerror = e => {\n    console.log(e.target.error); // Here is the error TS2339: Property does not exist\n  };\n};\n\nrequest.onerror = event => {\n  console.log(\'Error adding item\');\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

}

\n

dum*_*ter 5

这是 TypeScript 中的一个错误,请参阅https://github.com/microsoft/TypeScript/issues/30669

any您可以通过强制转换或使用或其他方式来解决它// @ts-ignore