Typescript对象的属性 [英] Typescript casting object's property

查看:555
本文介绍了Typescript对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用indexeddb和typescript。我的问题是TS似乎不能处理 event.target.result 属性。例子:

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();
}

所以我的问题是:有更简单的方法来投入目标属性到< IDBOpenDBRequest> 其他然后 a c $ c> b

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

推荐答案

如果你正在寻找一个oneliner它通过添加一些额外的括号,如此:

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;
}

也请注意:IDBDatabase ,因为结果在Typescript定义文件中被定义为 any 。它不是必需的,但使用它作为一个任何类型将意味着没有类型检查由编译器。

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.

现在你可以使用的结果,如下所示: http://www.w3.org/TR/IndexedDB/#database-interface

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

这篇关于Typescript对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆