打字稿对象的属性

时间:2014-12-15 18:22:51

标签: properties casting 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();
}

所以我的问题是:是否有更简单的方法将target属性转换为<IDBOpenDBRequest>,而不是上面的ab方法?

2 个答案:

答案 0 :(得分:11)

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

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

另请注意: IDBDatabase,因为在Typescript定义文件中将结果输入为any。它不是必需的,而是用它作为一个&#34;任何&#34;类型意味着编译器不会进行类型检查。

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

答案 1 :(得分:0)

您还可以像这样使用'as'关键字进行投射

interface MyCustomUserInterface {
    _id: string;
    name: string;
}

const userID = (req.user as MyCustomUserInterface)._id
...

干杯!

相关问题