How To Initialize JSON Array In TypeScript

JSON is a special notation type provided in JavaScript used to store objects. The article explains how to initialize JSON array in TypeScript with interfaces and classes.

Initialize JSON Array In TypeScript

Let’s start creating a JSON array followed by creating an interface.

Create an Interface

Declare an interface with the following fields. You can always change the fields as per your requirement.

Create a file named user-model.ts. You can rename it as per your project model.

user-model.ts

Note: The question mark (?) in the address field shows that it is declared as an optional field. Value for the field can be passed or leave it undefined at the time of initialization.

Initialize JSON Array objects with interface

Initialize the array of objects with the interface UserModel. Import the interface in json-example.ts file.

json-example.ts

Create the array data.

Log the users to see whether array of objects is created successfully.

Complete code here.

Output

Here is the Array of Objects output on Browser Console.

Initialized JSON Array In TypeScript
Initialized JSON Array In TypeScript

Final Say

Array initialization with the help of an interface is pretty easy. Interfaces make object/array initialization easy and fields typo error-free.

The article covers initialization of JSON array in typeScript using Interfaces.

Split string into Array using JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *