Why does TypeScript throw the error: TS2339: Property 'error' does not exist on type 'EventTarget'

Why does TypeScript throw the error: TS2339: Property 'error' does not exist on type 'EventTarget'

我尝试使用 IndexedDB 为一家小书店编写一个 angular 应用程序。 我将索引 'isbn' 设置为 unique 现在我尝试引发错误,因为我想告诉用户 isbn 必须是唯一的并且想显示错误消息.

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

活动

   {isTrusted: true, type: "error", 
   target: IDBRequest, currentTarget: IDBRequest, eventPhase: 2, …}

isTrusted: true
type: "error"
target: IDBRequest
result: undefined

error: DOMException: Unable to add key to index 'isbn': at least one key does not satisfy the uniqueness requirements.

问题:

我不能写 console.log(e.target.error) 因为 TypeScript 说: TS2339: 属性 'error' 在类型 'EventTarget'

上不存在

为什么?

#

这是方法:

addItem() {

const request = window.indexedDB.open(this.database.name);

request.onsuccess = event => {

  const item = {
    title: '',
    isbn: 1,
    descrition: '',
    rating:  1
  };

  const transaction = request.result.transaction(['books'], 'readwrite');
  const objectStore = transaction.objectStore('books');
  const objectStoreRequest = objectStore.add(item);

  objectStoreRequest.onerror = e => {
    console.log(e.target.error); // Here is the error TS2339: Property does not exist
  };
};

request.onerror = event => {
  console.log('Error adding item');
};

}

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

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