Ask Your Question
2

How to generate an array using an interface?

asked 2021-04-15 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-10-02 11:00:00 +0000

huitzilopochtli gravatar image

To generate an array using an interface, you can do the following:

  1. Define the interface. For example:
interface Person {
  name: string;
  age: number;
}
  1. Create an array of objects that implement the interface. For example:
const people: Person[] = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Bob", age: 40 }
];

This creates an array of Person objects with different values for the name and age properties.

  1. You can also generate the array dynamically using a function. For example:
function generatePeople(numPeople: number): Person[] {
  const people: Person[] = [];
  for(let i = 0; i < numPeople; i++) {
    people.push({
      name: `Person ${i}`,
      age: Math.floor(Math.random() * 50) + 20 // generate a random age between 20 and 69
    });
  }
  return people;
}

const people = generatePeople(5); // generates an array of 5 Person objects with random names and ages

This function generates a specified number of Person objects with random names and ages, and returns them as an array.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-04-15 11:00:00 +0000

Seen: 18 times

Last updated: Oct 02 '21