简体   繁体   English

在TypeScript中返回不同类型的数组

[英]Return an array of different types in TypeScript

In TypeScript 2.5.3 I've a bunch of selenium WebElements which are links. 在TypeScript 2.5.3中,我有一堆作为链接的硒WebElement。 I need to get their targets in an array of strings. 我需要将它们的目标存储在字符串数组中。 Caming from C# I would use Linq with .Select() which itself returns a list of the return type from the selector. 从C#出发,我将Linq与.Select() ,它本身从选择器返回返回类型的列表。 In Typescript this doesn't seem to work so nicely: 在Typescript中,这似乎不太好用:

    let categoryLinkElements = await this.driver.findElements(By.css('ul li a'));
    let categoryLinks = categoryLinkElements.filter(async linkElement => await linkElement.getAttribute('href'));

categoryLinkElements is an array of WebElement . categoryLinkElementsWebElement的数组。 And linkElement.getAttribute('href') returns Promise<string> . 并且linkElement.getAttribute('href')返回Promise<string> Cause await is used, I would expect that categoryLinks is an array of strings, like the same behavior of List.Select() in C#. 因为使用了await ,所以我希望categoryLinks是一个字符串数组,就像C#中List.Select()的相同行为一样。 Instead, categoryLinks is WebElement[] . 相反, categoryLinksWebElement[]

Why? 为什么? And how can I get the correct return value? 以及如何获得正确的返回值?

Array.filter seems wrong here, instead it should be used to return the same value than the input array, but with some filter condition. Array.filter在这里似乎是错误的,相反,它应该用于返回与输入数组相同的值,但带有一些过滤条件。 Instead Array.map is the correct equivalent of List.Select in C#. 而是Array.map是C#中List.Select的正确等效项。

The following works as expected: 预期的工作如下:

let categoryLinks = categoryLinkElements.map(async linkElement => await linkElement.getAttribute('href'));

As a beginner of Typescript and Javascript, this seems a stupid question afterwards... sorry :/ 作为Typescript和Javascript的初学者,此后似乎是一个愚蠢的问题...对不起:/

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

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