typescript 打字稿铸造对象的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27490535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:56:56  来源:igfitidea点击:

Typescript casting object's property

propertiescastingtypescript

提问by Eonasdan

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

我正在使用 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();
}

So my question is: Is there an easier way to cast the targetproperty to <IDBOpenDBRequest>other then the a, bmethod above?

所以我的问题是:有没有更简单的方法可以将target属性转换为<IDBOpenDBRequest>其他方法而不是上面的a,b方法?

回答by Dick van den Brink

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

如果您正在寻找 oneliner,您可以通过添加一些额外的括号来投射它,如下所示:

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

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

还要注意: IDBDatabase因为结果是any在 Typescript 定义文件中键入的。它不是必需的,但将其用作“任何”类型将意味着编译器不会进行类型检查。

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

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