【问题标题】:Typescript casting object's property打字稿铸造对象的属性
【发布时间】:2014-12-15 18:22:51
【问题描述】:

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

所以我的问题是:除了上面的ab 方法之外,有没有更简单的方法将target 属性转换为&lt;IDBOpenDBRequest&gt;

【问题讨论】:

    标签: properties casting typescript


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 谢谢。看到你的回答,我脸色苍白。我不知道为什么我没有想到这一点。像冠军一样工作。
    【解决方案2】:

    您也可以像这样使用“as”关键字进行投射

    interface MyCustomUserInterface {
        _id: string;
        name: string;
    }
    
    const userID = (req.user as MyCustomUserInterface)._id
    ...
    

    干杯!

    【讨论】:

      【解决方案3】:

      如果你需要链接,你可以这样做:

      const chargeId = (<Stripe.Invoice>subscription.latest_invoice).charge as string;
      

      ...具有 3 个属性:

          const paymentIntent = (<Stripe.Invoice>subscription.latest_invoice).payment_intent as Stripe.PaymentIntent;
          
          const secret = paymentIntent.client_secret;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-17
        • 1970-01-01
        • 2018-12-31
        • 1970-01-01
        • 2017-01-04
        • 2019-07-28
        • 2019-10-03
        • 2020-12-17
        相关资源
        最近更新 更多