Types के साथ for...of
In this page:
for (const item of iterable) {
// use item
}
Iterating Typed Arrays
for...of से एक array iterate करते समय, TypeScript loop variable का type directly array के element type से infer करता है, इसलिए एक string[] iterate करना आपको हर pass पर एक properly typed string देता है।
उदाहरण: Iterating Typed Arrays
const names: string[] = ["Ravi", "Priya"];
for (const name of names) {
console.log(name.toUpperCase());
}
Iterating Objects with Iterable Types
Plain objects for...of के साथ iterable नहीं होते जब तक वे explicitly iterable protocol implement न करें — arrays, strings, और built-in collection types ये सभी automatically qualify करते हैं, लेकिन एक bare {} literal कभी नहीं करता।
उदाहरण: Iterating Objects with Iterable Types
const arr = [1, 2, 3];
for (const n of arr) console.log(n);
// A bare {} literal is not iterable and would fail here.
for...of with Sets
Set<T> iterable है और हर pass पर type T की values yield करता है, इसलिए TypeScript loop के through वह element type बरकरार रखता है जिसके साथ Set declared था।
उदाहरण: for...of with Sets
const ids: Set<number> = new Set([1, 2, 3]);
for (const id of ids) {
console.log(id);
}
for...of with Maps
Map<K, V> अपनी entries पर [key, value] pairs के रूप में iterable है, इसलिए एक Map पर for...of में हर loop variable K और V रखने वाले दो-element tuple के रूप में infer होता है।
उदाहरण: for...of with Maps
const scores: Map<string, number> = new Map([["Ravi", 90], ["Priya", 85]]);
for (const [name, score] of scores) {
console.log(name, score);
}
for...of with Generators
Generators भी iterable sequences produce करते हैं, इसलिए एक generator yield करता है वह type for...of loop variable का inferred type बन जाता है जब आप directly एक generator के results पर iterate करते हैं।
उदाहरण: for...of with Generators
function* letters(): Generator<string> {
yield "a";
yield "b";
}
for (const letter of letters()) {
console.log(letter);
}
- एक plain object पर
for...ofउपयोग करना, जैसेfor (const x of {a: 1}), जो एक error है क्योंकि objects iterable नहीं हैं (इसके बजायfor...inयाObject.entriesउपयोग करें)। - Arrays पर
for...in(keys) कोfor...of(values) से confuse करना, इसलिए आपको indexes strings के रूप में मिलते हैं। - एक
Mapiterate करना और एक value की उम्मीद करना, जब हर item एक[key, value]pair है।
symboltype और unique symbols ऐसी values बनाते हैं जो guaranteed रूप से distinct हैं।- Iterator protocol define करता है कि objects पर कैसे loop किया जा सकता है।
- Generator और async generator functions values को lazily produce करते हैं, और
for...oftyped iterables के साथ काम करता है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: