TypeScript docs say nothing about loop like for
or for-in
. From playing with the language it seems that only any
or string
variables are supported in for
loop.
Why has this decision been made?
Why not use the type information and have strongly-typed iteration variable?
Difference for..in and for..of : Both for..in and for..of are looping constructs which are used to iterate over data structures. The only difference between them is the entities they iterate over: for..in iterates over all enumerable property keys of an object. for..of iterates over the values of an iterable object.
The for...in statements combo iterates (loops) over the properties of an object. The code block inside the loop is executed once for each property.
Using for (var property in array) will cause array to be iterated over as an object, traversing the object prototype chain and ultimately performing slower than an index-based for loop. for (... in ...) is not guaranteed to return the object properties in sequential order, as one might expect.
The initialization statement is executed before the loop begins. The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
In Typescript 1.5 and later, you can use for..of
as opposed to for..in
var numbers = [1, 2, 3]; for (var number of numbers) { console.log(number); }
TypeScript isn't giving you a gun to shoot yourself in the foot with.
The iterator variable is a string because it is a string, full stop. Observe:
var obj = {}; obj['0'] = 'quote zero quote'; obj[0.0] = 'zero point zero'; obj['[object Object]'] = 'literal string "[object Object]"'; obj[<any>obj] = 'this obj' obj[<any>undefined] = 'undefined'; obj[<any>"undefined"] = 'the literal string "undefined"'; for(var key in obj) { console.log('Type: ' + typeof key); console.log(key + ' => ' + obj[key]); }
How many key/value pairs are in obj
now? 6, more or less? No, 3, and all of the keys are strings:
Type: string 0 => zero point zero Type: string [object Object] => this obj; Type: string undefined => the literal string "undefined"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With