Typescript类型转换对象属性

16

我正在使用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方法?

3个回答

19

如果您在寻找一行代码,您可以通过添加一些额外的括号来实现:

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

同时注意到: IDBDatabase,因为在Typescript定义文件中结果类型为any,这并不是必需的,但是将其使用作为"any"类型会意味着编译器不进行类型检查。

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


1
谢谢。看到你的答案时,我感到非常惊讶。不知道为什么我没想到那个方法。现在它像个冠军一样运行。 - Eonasdan

1
你也可以使用 'as' 关键字进行转换,如下所示。
interface MyCustomUserInterface {
    _id: string;
    name: string;
}

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

干杯!


0
如果你需要链式操作,可以这样做:
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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接