Typescript casting object's property
Asked Answered
D

3

16

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

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

Denude answered 15/12, 2014 at 18:22 Comment(0)
L
20

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

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.

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

Longwinded answered 15/12, 2014 at 19:45 Comment(2)
Thanks. I face-palmed when I saw your answer. I don't know why I didn't think of that. Works like a champ.Denude
Someone else setting the parenthesis outside the cast and going crazy, like me? :( <IDBOpenDBRequest>(ev.target).resultLederman
S
1

You can also cast using the 'as' keyword like this

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

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

Cheers!

Subtraction answered 19/11, 2020 at 19:8 Comment(0)
B
0

If you need to chain, you can do this:

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

...with 3 properties:

    const paymentIntent = (<Stripe.Invoice>subscription.latest_invoice).payment_intent as Stripe.PaymentIntent;
    
    const secret = paymentIntent.client_secret;
Broyles answered 29/3, 2022 at 1:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.