Categories
TypeScript Answers

How to instantiate, initialize and populate an array in TypeScript?

Spread the love

Sometimes, we want to instantiate, initialize and populate an array in TypeScript.

In this article, we’ll look at how to instantiate, initialize and populate an array in TypeScript.

How to instantiate, initialize and populate an array in TypeScript?

To instantiate, initialize and populate an array in TypeScript, we can make a new class.

For instance, we write

class Bar {
  constructor(public length: number) {}
}

const bars = [new Bar(1)];

to define the Bar class that takes the length parameter in the constructor.

And it’ll assign the length value to the length instance property.

Then we define the bars array and assign it an array that has a Bar instance.

Conclusion

To instantiate, initialize and populate an array in TypeScript, we can make a new class.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.