简体   繁体   English

如何将泛型类型数组转换为 typescript 中的专用类型数组

[英]How to convert generic type array to specialized type array in typescript

I'm using firebase in my application.我在我的应用程序中使用 firebase。 So, the snapshotChanges() method of firebase returning an Observable of type SnapshotAction array which I want to convert to specific type array after subscribing to an Observable.因此,firebase 的 snapshotChanges() 方法返回一个 SnapshotAction 类型的 Observable 数组,我想在订阅 Observable 后将其转换为特定类型的数组。 So, how can we do this in typescript?那么,我们如何在 typescript 中做到这一点?

Have a look at codebase below to understand it better,查看下面的代码库以更好地理解它,

 // Below observable is returned by firebase snapshotChanges() method Observable<SnapshotAction<Product>[]> // Now, after I subscribe to the above observable I get below type, SnapshotAction<Product>[] // Now I want to convert "SnapshotAction<Product>[]" to "Product[]" in typescript

Snapshot action has a payload field which will give you a快照操作有一个有效负载字段,它将为您提供

DatabaseSnapshot<Product>

A DatabaseSnapshot has a val() method which will return a Product or null depending if the snapshot exists. DatabaseSnapshot 有一个 val() 方法,该方法将返回 Product 或 null ,具体取决于快照是否存在。 So you can write a small function like this to extract the product:所以你可以像这样写一个小 function 来提取产品:

function example(input: SnapshotAction<string>[]): (string | null)[] {
    return input.map(action => action.payload.val())
}

Note that this is return string |请注意,这是返回字符串 | null because the snapshot might not exist. null 因为快照可能不存在。 You could look at你可以看看

action.payload.exists()

If you want to do additional checks or filtering.如果您想进行额外的检查或过滤。

 products: Product[] = []; this.productService.getAll().pipe( switchMap((products: SnapshotAction<Product>[]) => { // Our intention starts here products.map(product => { let prod: Product = product.payload.val(); prod.key = product.key; this.products.push(prod); }); }); );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM