for comprehension in typescript

In TypeScript, a for comprehension is used to loop through an iterable object (such as an array) and apply a function to each element in the object. The resulting values are then combined and returned in a new iterable object. The for comprehension is often used in functional programming to transform collections of data.

Here's an example of a basic for comprehension in TypeScript:

index.ts
const myArray = [1, 2, 3, 4, 5];

const result = [for (x of myArray) x * 2];

console.log(result); // Output: [2, 4, 6, 8, 10]
127 chars
6 lines

In this example, we create an array of numbers and apply a for comprehension to it. The for loop runs through each element in the array and multiplies it by 2. The resulting values are then returned as a new array.

Note that the for comprehension syntax in TypeScript is similar to that in other languages like Scala, but with some minor differences to accommodate TypeScript's static typing.

gistlibby LogSnag