Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript casting object's property

I'm working with indexeddb and typescript. My issue is that TS doesn't seem to be able handle the event.target.result property. Case in point:

request.onsuccess = (event) => {
    namespace.db = event.target.result; //the property 'results' does not 
                                        //exist on the value of type 'EventTarget'
    var a = event.target;
    var b = <IDBOpenDBRequest>a;
    var c = b.result; // <-- magically there's a results property here

    version = parseInt(namespace.db.version);
    console.log("version: " + version);
    deferred.resolve();
}

So my question is: Is there an easier way to cast the target property to <IDBOpenDBRequest> other then the a, b method above?

like image 295
Eonasdan Avatar asked Dec 15 '14 18:12

Eonasdan


People also ask

How do you typecast an object in TypeScript?

A straightforward way to cast a variable is using the as keyword, which will directly change the type of the given variable.

Can you cast in TypeScript?

Converting a variable from one type to another is possible with type casting in Typescript. Type casting in TypeScript can be done with the 'as' keyword or the '<>' operator.

How do you check if an object has a property in TypeScript?

To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.


1 Answers

If you are looking for a oneliner you can cast it by adding some extra parenthesis like so:

indexedDB.open("test", 1).onsuccess = (ev) => {
    var result: IDBDatabase = (<IDBOpenDBRequest>ev.target).result;
}

Also notice the : IDBDatabase because result is typed as any in the Typescript definition file. It isn't needed but using it as an "any" type would mean no typechecking by the compiler.

Now you can use the result like you want with the methods available as defined here: http://www.w3.org/TR/IndexedDB/#database-interface

like image 149
Dick van den Brink Avatar answered Sep 24 '22 20:09

Dick van den Brink