Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you declare an array of objects inside typescript?

I would like to specify a function that takes an array of objects as a parameter, but I don't have a particular type defined for the object (a sort of "anonymous type")

bagTotal = (products) => {
 // function does stuff
}

I understand I can do this:

bagTotal = (products: any[]) => {
 // function does stuff
}

but this is a bit more relaxed then what I want: to be strict with typescript.

products is an array of the same-looking objects; all objects have a name, a price and a description.

how can I declare that?

I want to do something like

bagTotal = (products: [{name: string, price: number, description: string}]) => {
 // function does stuff
}

but that's not right. How can I declare this?

like image 922
Red Baron Avatar asked Dec 28 '18 21:12

Red Baron


People also ask

Should I use [] or array in TypeScript?

There is no difference at all. Type[] is the shorthand syntax for an array of Type . Array<Type> is the generic syntax. They are completely equivalent.

How do you declare array of objects in JavaScript?

To initialize an array of objects, use the Array() constructor to create an array filled with N empty elements and use a for loop to iterate over the array assigning each element to an object. Copied! const arr2 = new Array(2); for (let i = 0; i < arr2.

How do you define object of objects type in TypeScript?

In TypeScript, object is the type of all non-primitive values (primitive values are undefined , null , booleans, numbers, bigints, strings). With this type, we can't access any properties of a value.

Can you have an array of objects in JavaScript?

JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array.


2 Answers

You're almost there, the placement of the brackets is just wrong:

{name: string, price: number, description: string}[]

The way you had it isn't entirely wrong, but it means something else: it means an array with exactly one item of this type.


I'd also recommend extracting it to an interface, it'd make the type reusable and the thing easier to read:

interface Product {
    name: string;
    price: number;
    description: string;
}

const products: Product[];
like image 90
Ingo Bürk Avatar answered Sep 21 '22 17:09

Ingo Bürk


I think you must declare the class "Product" so you can declare a Product array like this:

products: Product[];

and pass it as a parameter like this:

bagTotal = (products: Product[]) => {
 // function does stuff
}

To have the class you can do a new .ts file with this code:

export class Product {
  name: String;
  price: Number;
  description: String;
}

I wish that helped!

Thank you.

like image 32
bautigaraventa Avatar answered Sep 17 '22 17:09

bautigaraventa