EN
Typescript - iterate over Record type
3 points
In this article, we would like to show you how to iterate over Record type in TypeScript.
Quick solution:
xxxxxxxxxx
1
for (const key in recordName) {
2
console.log(recordName[key]);
3
}
In this example, we use for...in
statement to iterate over the record.
xxxxxxxxxx
1
const record: Record<string, number> = { A: 65, B: 66, C: 67 };
2
3
for (const key in record) {
4
const value = record[key];
5
console.log(key + ': ' + value);
6
}
Output:
xxxxxxxxxx
1
A: 65
2
B: 66
3
C: 67
In this example, we get keys before to be able iterate over the record.
xxxxxxxxxx
1
const record: Record<string, number> = { A: 65, B: 66, C: 67 };
2
3
const keys = Object.keys(record);
4
for (let i = 0; i < keys.length; ++i) {
5
const key = keys[i];
6
const value = record[key];
7
console.log(key + ': ' + value);
8
}
Output:
xxxxxxxxxx
1
A: 65
2
B: 66
3
C: 67