Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get event.target.result in javascript indexdb typescript working?

In my javascript/typescript project I have this code

        request.onupgradeneeded = (event: IDBVersionChangeEvent) => {
            console.log('idb onupgradeneeded firing');
            const db = event.target.result;
            //if (db != null) {
                //console.log(`Upgrading to version ${db.version}`);
                if (!request.result.objectStoreNames.contains(this.#name)) {
                    request.result.createObjectStore(this.#name, {keyPath: 'id', autoIncrement:true});
                }
            //}
        };

But the problem is this code

event.target.result;

Shows an underline saying Property 'result' does not exist on type 'EventTarget'.

How can I fix this in typescript?

like image 602
omega Avatar asked Oct 27 '25 04:10

omega


1 Answers

There's not enough type information in handler callback type provided by dom Typescript library.

Probably you can define your own typing for indexedDB.open, but it looks much simpler to just downcast target manually:

const db = (event.target as IDBOpenDBRequest).result;

Or, as @kelsny suggested, use the original request object:

const db = request.result; // event.target === request
like image 138
Adamovskiy Avatar answered Oct 29 '25 17:10

Adamovskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!