Typescript casting object's property

寵の児 提交于 2019-12-21 03:58:26

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/27490535/typescript-casting-objects-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!