How to create an array of objects in TypeScript

I am looking to define an array of objects in TypeScript. Here is my example:

const a = [{
  name: 1,
  age: 2,
  car1: 8,
  car2: 8,
  car3: 8,
  name4: 1,
  age4: 2,
  car41: 8,
  car42: 8,
  car34: 8,
},
{
  name: 1,
  age: 2,
  car1: 8,
  car2: 8,
  car3: 8,
  name4: 1,
  age4: 2,
  car41: 8,
  car42: 8,
  car34: 8,
}
]

const fun = (obj: Array<object>) => {
  console.log(obj)
}

fun(a)

Is it correct for me to use the syntax obj: Array<object> or should I individually define each key of my object?

Answer №1

The outcome of your question relies on the specific scenario you aim to program in! Presented below are a few potential scenarios utilizing your code.

Start by defining an object and inferring its keys from it.

const people = [
  { name: "Sarah", age: 30 },
  { name: "Alex", age: 25 }
];

const printInfo = (data: typeof people) => {
  //Intellisense will be available here
  console.log(data[0].name);
};

If you desire objects with fixed keys, types and interfaces can be utilized for that purpose.

interface IPerson {
  id?: string; // ID is optional 
  name: string; // Name is required
  age: number;
}

const persons: Array<IPerson> = [
  { name: "Sarah", age: 30 },
  { name: "Alex", age: 25 }
];

// Both statements are equivalent: Array<IPerson> === IPerson[]
const printInfo = (data: Array<IPerson>) => {
  //Intellisense will be available here
  console.log(data[0].name);
};

If you want an object with fixed keys but wish to provide partial information, check out the following example.

interface IPerson {
  id?: string;
  name: string;
  age: number;
}

const persons: Array<Partial<IPerson>> = [
  { name: "Sarah" }, 
  { name: "Alex", age: 25 }
];

// Both statements are equivalent: Array<IPerson> === IPerson[]
const printInfo = (data: Partial<IPerson>[]) => {
  //Intellisense will be available here
  console.log(data[0].name);
};

Keep in mind, Typescript supports type checking at compile time only, not during runtime.

To implement runtime type validation, consider using the function provided below:

const isValidPerson = (person: any): Boolean => {
  return (
    typeof person === "object" &&
    typeof person.name === "string" &&
    typeof person.age === "number" &&
    person.name.length >= 5 &&
    person.age >= 1
  );
};

console.log("Is person valid? ", isValidPerson({}));
console.log("Is person valid? ", isValidPerson("Invalid Person"));

Hopefully one of the approaches mentioned above will resolve your issue.

In my situation, is it correct to use the construction 'obj: Array' or should I define each key of my object?

The answer to the above question is:

  • You can utilize any of the methods shown above. Typescript aids in writing more precise code and reducing mistakes during compilation. Once compiled, your code transforms into plain Javascript, which does not validate your responses.

  • All presented patterns result in the same JavaScript code, so there are no performance concerns.

Answer №2

Upon reviewing the documentation, it becomes apparent that relying on object may be perceived as taking a shortcut.

If all objects within an array share the same properties, this issue can be addressed in the following manner:

interface UserWithCars {
  name: number;
  age: number;
  // Additional properties
}

const processObjects = (objectArray: Array<UserWithCars>): void => {
  console.log(objectArray);
}

In scenarios where objects are of identical types, creating a class is highly recommended:

class UserWithCars {
  name: number;
  age: number;
  // Additional properties

  constructor(/* parameters */) {
    // Constructor logic
  }
}

const processObjects = (objectArray: Array<UserWithCars>): void => {
  console.log(objectArray);
}

Answer №3

If you want to define a new object type, you can create a custom one like this:

type NewObject = {
  title: string
  year: number
  genre: string
}

const arrayOfNewObjects: NewObject[] = [{
  title: 'Movie A',
  year: 2020,
  genre: 'Action'
},
{
  title: 'Movie B',
  year: 2018,
  genre: 'Comedy'
}
]

const displayObjects = (objects: NewObject[]) => {
    objects.forEach((object) => {
        console.log(object)
    })
}

displayObjects(arrayOfNewObjects)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The directive [ngTemplateOutet] is functioning properly, however, the directive *ngTemplateOutlet is not functioning as expected

I have been struggling to create a component using ngTemplateOutlet to select an ng-template, but for some reason *ngTemplateOutlet is not working in this case (although [ngTemplateOutlet] is functioning correctly). Below is the code I am currently using: ...

Encountering an error stating "cloudinary.uploader is undefined" while attempting to delete media files from Cloudinary

I'm currently developing a web application using express and node.js. In my project, I'm utilizing cloudinary for uploading media files. While uploading and accessing media works smoothly, I'm encountering an issue with deleting images from ...

navigation bar: retain link hover state even after displaying sub-menu

My navigation bar has submenus with background images in .png format. Only 3 links in my navbar have these submenus. The issue I am facing is that when the menu link is in a hover state and the submenu is being hovered over, the nav link loses its hover st ...

Use the column name instead of the index with Jquery's eq() function

Looking for a way to use a static column name in jQuery to get the 5th column text in a table and change the text of a textbox $('textbox').val($(e.target).closest("tr").find('td:eq(4)').text()); If the index of the columns is changed ...

Creating QR codes from raw byte data in TypeScript and Angular

I have developed a basic web application that fetches codes from an endpoint and generates a key, which is then used to create a QR Code. The key is in the form of an Uint8Array that needs to be converted into a QR Code. I am utilizing the angularx-qrcode ...

Design an element that stretches across two navigation bars

Currently, I have implemented two Navbars on my website as shown in the image below: https://i.stack.imgur.com/4QmyW.png I am now looking to include a banner that clearly indicates that this site is a test site. In addition, I would like to incorporate a ...

Attempting to modify the key values within an object, however, it is mistakenly doubling the values instead

I'm encountering an issue when trying to update key values within an object. It seems to be adding duplicate values or combining all values together instead of assigning each name a specific language slug. I can't figure out where I'm going ...

`There is a delay in rendering the background image on Chrome`

Once I apply a class to my button element using JavaScript, the background image (.gif) that is supposed to display afterwards takes an unusually long time to render. The button serves as a form submission. Upon being clicked, a class of "clicked" is dyna ...

Verifying authentication on the server and redirecting if not authorized

I am working on my NEXTJS project and I want to implement a feature where the cookie headers (httponly) are checked and the JWT is validated server-side. In case the user is not logged in, I would like to respond with a 302 redirect to /login. I'm unc ...

Issue with Ionic 4 IOS deeplinks: Instead of opening in the app, they redirect to the browser

After working diligently to establish deeplinks for my Ionic 4 iOS application, I meticulously followed a series of steps to achieve this goal: I uploaded an Apple site association file to the web version of the app, ensuring the utilization of the prec ...

How can I retrieve data submitted in a POST request on my Node.js server

I'm having trouble sending form data to a node/express server using AJAX. After submitting, I keep getting redirected to a 'Cannot POST /' page. Although I can log the request object on the server side, the data from the form is missing. Wha ...

Top method for utilizing render props in React

Currently, I am employing render model props. However, I have a hunch that there might be an alternative method to achieve the same outcome. Is anyone familiar with another approach? {variable === "nameComponen" && <component/>} {variable === "name ...

Issue: While trying to add a new component to a formArray, the formGroup function requires an instance of FormGroup

I am currently implementing the Reactive Forms Approach in my project. Within a form (with the parent component named: DeductionInvoicesComponent), I have the following structure: <form [formGroup]="deductionForm"> <div formArrayName="items ...

How to deal with an empty $_FILES array when there is file data present in $_POST

After reviewing multiple solutions, I noticed that they all utilize jQuery's .ajax() method. However, I have developed a more concise vanilla JS approach which has been quite successful for me. function ajax(options){ var settings = { met ...

JavaScript for URL encoding

Hey there, I've been using the function below to encode my data and send it through the GET method. I'm utilizing AJAX for sending and PHP for receiving. function urlencode(a){ a=encodeURIComponent(a); a=a.replace(/\\/g,&apos ...

I'm looking to receive the specific data types for express request arguments. How can I

Currently, I am working on incorporating authentication into an express application using passport and typescript. For defining the user model, I have utilized typegoose. Once the login request passes through the passport strategy, a login method is called ...

Steps for embedding a font in a .pptx file

While working on creating a .pptx file using ASPOSE.Slides, I encountered some issues with embedding fonts. As an alternative option, I am looking for suggestions on how to embed custom fonts in a .pptx file using Apache POI or other methods. If you have ...

The value of req.files consistently shows as undefined

My issue is with req.files consistently returning undefined. Despite attempting connect-multiparty, body-parser, and express-fileupload, I can't seem to make it work with express-fileupload instead of multer. Can anyone help me troubleshoot this probl ...

The Angular 2 service is not transmitting the POST data in the correct format, although it functions properly when transmitted through PostMan

When the POST data is transmitted from the Angular 2 service in this manner: const data = new FormData(); data.append('date', '12/01'); data.append('weight', '170'); return this.http.post(this.u ...