打字稿对象的属性

Eon*_*dan 10 casting properties typescript

我正在使用indexeddb和typescript.我的问题是TS似乎无法处理该event.target.result属性.例证:

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();
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:有没有到铸造一个更简单的方法target属性<IDBOpenDBRequest>等那么a,b上述方法?

Dic*_*ink 13

如果您正在寻找oneliner,可以通过添加一些额外的括号来强制转换它:

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

另请注意,: IDBDatabase因为any在Typescript定义文件中键入了result.它不是必需的,但是将它用作"任何"类型意味着编译器不会进行类型检查.

现在,您可以使用此处定义的可用方法使用您想要的结果:http://www.w3.org/TR/IndexedDB/#database-interface