iterate over record in typescript

We can use the for...in loop to iterate over a TypeScript record or object.

Here's an example:

index.ts
const personRecord: Record<string, string> = {
  name: "John",
  age: "30",
  occupation: "Developer"
};

for (const key in personRecord) {
  console.log(`${key}: ${personRecord[key]}`);
}
189 chars
10 lines

In this example, we have a record personRecord with three key-value pairs. We use a for...in loop to iterate over the keys of the record, and log each key and its corresponding value to the console.

Note that we've given the personRecord variable a type of Record<string, string>, which means it's a record with string keys and string values. If your record has different data types for its keys and values, you'll need to adjust the type accordingly.

gistlibby LogSnag