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
export interface UserModel {
userId: number;
username: string;
email: string;
name: string;
address?: string;
}
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
import { UserModel } from './user-model';
Create the array data.
const users: UserModel[] = [
{
userId: 123,
username: 'mac',
email: 'mac@email.com',
name: 'Mac',
},
{
userId: 234,
username: 'john',
email: 'john@doe.com',
name: 'John Doe',
},
{
userId: 345,
username: 'jameer',
email: 'jameer@email.com',
name: 'Jameer',
},
];
Log the users
to see whether array of objects is created successfully.
console.log(users);
Complete code here.
import { UserModel } from './user-model';
const users: UserModel[] = [
{
userId: 123,
username: 'mac',
email: 'mac@email.com',
name: 'Mac',
},
{
userId: 234,
username: 'john',
email: 'john@doe.com',
name: 'John Doe',
},
{
userId: 345,
username: 'jameer',
email: 'jameer@email.com',
name: 'Jameer',
},
];
console.log(users);
Output
Here is the Array of Objects output on Browser Console.
Final Say
Array initialization with the help of an interface is pretty easy. Interfaces make object/array initialization easy and field typos error-free.
The article covers initialization of JSON array in typeScript using Interfaces.