Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to Clone an Array in TypeScript ?
Next article icon

How can I Define an Array of Objects in TypeScript?

Last Updated : 20 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In TypeScript, the way of defining the arrays of objects is different from JavaScript. Because we need to explicitly type the array at the time of declaration that it will be an Array of objects. In this article, we will discuss the different methods for declaring an array of objects in TypeScript.

There are many methods of declaring an array of objects in TypeScript as listed below:

Table of Content

  • Using the inline type declaration
  • Using the in-built interfaces and type
  • Using the built-in Array type
  • Using the typeof operator
  • Using Mapped Types and Generics

Using the inline type declaration

In this method, we will use an object literal with some pre-defined keys and values to explicitly type the array as an array of objects and then assign the values to the properties of the object.

Syntax:

const array_name: {key1: type1, key2: type2, key3: type3}[] = [{}];

Example: The below example will explain how you can define an array of objects using inline typing.

JavaScript
let myArr: {     cktr_name: string, cktr_team: string,     cktr_runs: number }[] = [         {             cktr_name: "Virat Kohli",             cktr_team: "India",             cktr_runs: 26000         },         {             cktr_name: "AB De Villiers",             cktr_team: "South Africa",             cktr_runs: 15000         },         {             cktr_name: "David Warner",             cktr_team: "Australia",             cktr_runs: 13000         }     ];  myArr.forEach((cktr) => {     console.log(`Hi, My name is ${cktr.cktr_name},     I play for ${cktr.cktr_team} and      I've already made ${cktr.cktr_runs}     runs while representing my country.`) }) 

Output:

Hi, My name is Virat Kohli, I play for India and I've already made 26000 runs while representing my country. Hi, My name is AB De Villiers, I play for South Africa and I've already made 15000 runs while representing my country. Hi, My name is David Warner, I play for Australia and I've already made 13000 runs while representing my country.

Using the in-built interfaces and type

In this approach, first we will define the format of the object inside a interface ot type defined using the respective kerwords. While defining interfaces or type, we will provide the property names and their types inside them and assign them as a explicit type the array.

Syntax:

interface/ type interface_name{     key1: type1,     key2: type2,     key3: type3 } const array_name: interface_name = [];

Example: The below example will illustarte the use of the interfaces to define an array of objects, you can declare interface as type and can use type also for the same purpose.

JavaScript
interface Cricketer {     cktr_name: string,     cktr_team: string,     cktr_runs: number } const cktr1 = {     cktr_name: "Virat Kohli",     cktr_team: "India",     cktr_runs: 26000 } const cktr2 = {     cktr_name: "AB De Villiers",     cktr_team: "South Africa",     cktr_runs: 15000 } const cktr3 = {     cktr_name: "David Warner",     cktr_team: "Australia",     cktr_runs: 13000 }  const myArr: Cricketer[] = [cktr1, cktr2, cktr3];  myArr.forEach((cktr) => {     console.log(`Hi, My name is ${cktr.cktr_name},     I play for ${cktr.cktr_team} and      I've already made ${cktr.cktr_runs}      runs while representing my country.`) }) 

Output:

Hi, My name is Virat Kohli, I play for India and I've already made 26000 runs while representing my country.  Hi, My name is AB De Villiers, I play for South Africa and I've already made 15000 runs while representing my country.  Hi, My name is David Warner, I play for Australia and I've already made 13000 runs while representing my country.

Using the built-in Array type

We can also use the built-in Array type to define an array of object in TypeScript.

Syntax:

const array_name: Array<{key1: type1, key2: type2, key3: type3}> = [{}];

Example: This example will show you the use of the Array type to create an array of object in TypeScript.

JavaScript
let myArr: Array<{     cktr_name: string,     cktr_team: string, cktr_runs: number }> = [         {             cktr_name: "Virat Kohli",             cktr_team: "India",             cktr_runs: 26000         },         {             cktr_name: "AB De Villiers",             cktr_team: "South Africa",             cktr_runs: 15000         },         {             cktr_name: "David Warner",             cktr_team: "Australia",             cktr_runs: 13000         }     ];  myArr.forEach((cktr) => {     console.log(`Hi, My name is ${cktr.cktr_name},     I play for ${cktr.cktr_team} and      I've already made ${cktr.cktr_runs}      runs while representing my country.`) }) 

Output:

Hi, My name is Virat Kohli, I play for India and I've already made 26000 runs while representing my country.  Hi, My name is AB De Villiers, I play for South Africa and I've already made 15000 runs while representing my country.  Hi, My name is David Warner, I play for Australia and I've already made 13000 runs while representing my country.

Using the typeof operator

In this method, we will first create an JavaScript object with some key value pairs inside it and then explicitly assign the type of that object to the array using the typeof operator and built-in array type.

Syntax:

const obj_name = {     key1: val1,     key2: val2 } const array_name: Array<typeof obj_name> = [{}]

Example: The below example will explain the above approach practically.

JavaScript
const cktr1 = {     cktr_name: "Virat Kohli",     cktr_team: "India",     cktr_runs: 26000 } const cktr2 = {     cktr_name: "AB De Villiers",     cktr_team: "South Africa",     cktr_runs: 15000 } const cktr3 = {     cktr_name: "David Warner",     cktr_team: "Australia",     cktr_runs: 13000 }  const myArr: Array<typeof cktr1> = [cktr1,     cktr2, cktr3];  myArr.forEach((cktr) => {     console.log(`Hi, My name is ${cktr.cktr_name},     I play for ${cktr.cktr_team} and      I've already made ${cktr.cktr_runs}      runs while representing my country.`) }) 

Output:

Hi, My name is Virat Kohli, I play for India and I've already made 26000 runs while representing my country.  Hi, My name is AB De Villiers, I play for South Africa and I've already made 15000 runs while representing my country.  Hi, My name is David Warner, I play for Australia and I've already made 13000 runs while representing my country.

Using Mapped Types and Generics

Mapped types allow you to create new types by transforming properties of an existing type, and generics enable you to define types that can work with various types of data. By combining these two features, you can create a generic type for arrays of objects that can be reused with different object structures.

Syntax:

type ArrayOf<T> = {     [K in keyof T]: T[K]; }[]; const array_name: ArrayOf<{ key1: type1; key2: type2; key3: type3 }> = [];

Example:

JavaScript
type Cricketer = {   cktr_name: string;   cktr_team: string;   cktr_runs: number; };  type ArrayOf<T> = T[];  const myArr: ArrayOf<Cricketer> = [   {     cktr_name: "Virat Kohli",     cktr_team: "India",     cktr_runs: 26000,   },   {     cktr_name: "AB De Villiers",     cktr_team: "South Africa",     cktr_runs: 15000,   },   {     cktr_name: "David Warner",     cktr_team: "Australia",     cktr_runs: 13000,   }, ];  myArr.forEach(({ cktr_name, cktr_team, cktr_runs }) => {   console.log(`Hi, I'm ${cktr_name} from ${cktr_team}, with                 ${cktr_runs} runs for my country.`); }); 

Output:

Hi, I'm Virat Kohli from India, with 26000 runs for my country.
Hi, I'm AB De Villiers from South Africa, with 15000 runs for my country.
Hi, I'm David Warner from Australia, with 13000 runs for my country.

Next Article
How to Clone an Array in TypeScript ?

A

abhish8rzd
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript

Similar Reads

  • How to Convert an Array of Objects into Object in TypeScript ?
    Converting an array of objects into a single object is a common task in JavaScript and TypeScript programming, especially when you want to restructure data for easier access. In this article, we will see how to convert an array of objects into objects in TypeScript. We are given an array of objects
    3 min read
  • How to Clone an Array in TypeScript ?
    A cloned array is an array that contains all the items or elements contained by an already existing array in the same order. A cloned array does not affect the original array. If there is any change made in the cloned array it will not change that item in the original array. We can use the following
    5 min read
  • How to Create an Object in TypeScript?
    TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data. Creating Objects in TypescriptNow, let
    4 min read
  • How to Declare a Fixed Length Array in TypeScript ?
    To declare a Fixed-length Array in TypeScript you can use a Tuple. Tuple types allow you to specify the types for each element in the array and, importantly, define a fixed number of elements in a specific order. In this article, we are going to learn how to declare a fixed-length array in TypeScrip
    3 min read
  • How to Check if an Array Includes an Object in TypeScript ?
    In TypeScript, checking if an array includes an object consists of comparing the object's properties within the array elements. We can compare and check this using three different approaches some method, find method, and includes method. There are several ways to check if an array includes an object
    3 min read
  • Sort an array of objects in typescript?
    We can achieve the sorting in TypeScript using the sort() function which is an inbuilt TypeScript function that is used to sort the elements of an array. Below are a few examples showing the sorting in TypeScript. Example 1: In this example, we will learn how to use the sort function to sort the arr
    3 min read
  • How to Iterate Array of Objects in TypeScript ?
    In TypeScript, we can iterate over the array of objects using various inbuilt loops and higher-order functions, We can use for...of Loop, forEach method, and map method. There are several approaches in TypeScript to iterate over the array of objects which are as follows: Table of Content Using for..
    4 min read
  • How to Declare an Array of Strings in TypeScript ?
    Arrays are fundamental data structures in TypeScript, enabling developers to manage collections of elements efficiently. Below are the approaches to declare an Array of strings in TypeScript: Table of Content Square Brackets NotationArray ConstructorSquare Brackets NotationUsing square brackets nota
    1 min read
  • How to Declare an Empty Array in TypeScript?
    TypeScript provides a robust type system that allows you to define and manage data structures more effectively than in plain JavaScript. One common task is declaring empty arrays with specific types, ensuring that your array holds only values of the intended type. These are the following ways to dec
    2 min read
  • How to Convert a Set to an Array in TypeScript ?
    A Set in TypeScript is used to create a particular type of list that does not contain duplicate elements. If any element is repeated more than once it will automatically remove the duplicate existence and consider it only once in the list. In this article, we will convert these types of lists into a
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences