Typescript создать массив объектов

How to create an array of objects in TypeScript

Array of objects can be defined in TypeScript to store data of a specific type in a sequential way. Similar to string, int or any other array, we can also have an array of objects. It is actually helpful if you are storing data in object-oriented way.

We can create an array of objects in different ways. Let me show you all one by one.

Method 1: Inline initialization of an array of objects:

Let’s take a look at the below example:

let students = [ name: 'Alex', age: 20 >,  name: 'Bob', age: 21 >,  name: 'Charlie', age: 20 >];

students is an array of objects. We have not defined any type here, but it will take the type implicitely.

let students: name: string, age: number>[] = [ name: 'Alex', age: 20 >,  name: 'Bob', age: 21 >,  name: 'Charlie', age: 20 >]; console.log(students);

We are printing the content of students on console. It will print the below output:

[  name: 'Alex', age: 20 >,  name: 'Bob', age: 21 >,  name: 'Charlie', age: 20 > ]

Method 2: Initializing an array of objects with optional properties:

In the above example, name and age are required for each objects. If we don’t have any of them in any object, it will throw one error.

typescript showing error

We can mark any property optional to remove this error.

let students: name: string, age?: number>[] = [ name: 'Alex', age: 20 >,  name: 'Bob', age: 21 >,  name: 'Charlie', >]; console.log(students);

In this example, the third object doesn’t have age. It will not show any error because we have marked age as optional.

Method 3: Creating an array of objects with an interface:

In typescript, we can also create one array of objects with the type defined by an interface. The interface will hold the structure of each objects and in the array we can initialize it as this type.

interface Student name: string; age?: number; > let students: Student[] = [ name: 'Alex', age: 20 >,  name: 'Bob', age: 21 >,  name: 'Charlie', >]; console.log(students);

In this example, Student interface holds one name of type string and optional age of type number. We are using the interface instead of the object type defined in previous examples.

Method 4: Creating an array of objects with type alias:

It is almost similar to interfaces. We can use a type alias instead of an interface.

=  name: string; age?: number; > let students: Student[] = [ name: 'Alex', age: 20 >,  name: 'Bob', age: 21 >,  name: 'Charlie', >]; console.log(students);

It will give similar result.

Instead of interfaces, we can also use a class to define objects of that class type.

class Student name: string; age?: number; constructor(n: string, a?: number) this.name = n; this.age = a; > > let students: Student[] = [new Student('Alex', 20), new Student('Bob', 21), new Student('Charlie')]; console.log(students);

Student is a class with two properties similar to the previous interface. We are creating new Student objects and inserting them to the array.

[ Student  name: 'Alex', age: 20 >, Student  name: 'Bob', age: 21 >, Student  name: 'Charlie', age: undefined > ]

Since all are Student class objects, the print output is bit different than the previous example.

We can use all array operations in an array of objects. For example, the below example uses map to iterate over the items and prints the name for each:

class Student name: string; age?: number; constructor(n: string, a?: number) this.name = n; this.age = a; > > let students: Student[] = [new Student('Alex', 20), new Student('Bob', 21), new Student('Charlie')]; students.map(s =>  console.log(s.name); >)

It is an array, so all operations supported by typescript array can be performed.

Источник

How can I define an array of objects?

Can someone tell me how I could declare its type correctly? Is it possible to do inline or would I need two definitions? I’m looking to replace the xxx with a type declaration, so that later on TypeScript would alert me if I used something like userTestStatus[3].nammme by mistake.

9 Answers 9

You are better off using a native array instead of an object literal with number-like properties, so that numbering (as well as numerous other array functions) are taken care of off-the-shelf.

What you are looking for here is an inline interface definition for your array that defines every element in that array, whether initially present or introduced later:

let userTestStatus: < id: number, name: string >[] = [ < "id": 0, "name": "Available" >, < "id": 1, "name": "Ready" >, < "id": 2, "name": "Started" >]; userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [. ] 

If you are initializing your array with values right away, the explicit type definition is not a necessity; TypeScript can automatically infer most element types from the initial assignment:

let userTestStatus = [ < "id": 0, "name": "Available" >, . ]; userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [. ] 

@Sujoy same as in JS, i.e. userTestStatus.push — it will also be type safe based on the initial assignment or type definition.

What you have above is an object, not an array.

To make an array use [ & ] to surround your objects.

Aside from that TypeScript is a superset of JavaScript so whatever is valid JavaScript will be valid TypeScript so no other changes are needed.

Feedback clarification from OP. in need of a definition for the model posted

You can use the types defined here to represent your object model:

type MyType = < id: number; name: string; >type MyGroupType = < Typescript создать массив объектов: MyType; >var obj: MyGroupType = < "0": < "id": 0, "name": "Available" >, "1": < "id": 1, "name": "Ready" >, "2": < "id": 2, "name": "Started" >>; // or if you make it an array var arr: MyType[] = [ < "id": 0, "name": "Available" >, < "id": 1, "name": "Ready" >, < "id": 2, "name": "Started" >]; 

Sorry maybe my question was not clear. What I wanted to do was to find a definition for userTestStatus.

@Marilou You can usually get the definition simply by hovering over the userTestStatus variable in your favourite IDE. the TypeScript playground shows < id: number, name: string; >[] . You could wrap that in an interface if you like interface NameThis < id: number, name: string; >and NameThis[] as the array type.

I tried this but it gives me a few errors. However I think it’s something like I want: userTestStatus: < id: number, name: string; >[] = < "0": < "id": 0, "name": "Available" >, «1»: < "id": 1, "name": "Ready" >,

In your example defining var arr: MyType , you wouldn’t use the property name/index declarations such as «0»: < … >; you would just use the object literal at this point.

Some tslint rules are disabling use of [], example message: Array type using ‘T[]’ is forbidden for non-simple types. Use ‘Array’ instead.

Then you would write it like:

var userTestStatus: Array> = Array( < "id": 0, "name": "Available" >, < "id": 1, "name": "Ready" >, < "id": 2, "name": "Started" >); 

Please try to explain your answer instead of just providing code—this helps the OP learn and also helps others who visit your answer.

What you really want may simply be an enumeration

If you’re looking for something that behaves like an enumeration (because I see you are defining an object and attaching a sequential ID 0, 1, 2 and contains a name field that you don’t want to misspell (e.g. name vs naaame), you’re better off defining an enumeration because the sequential ID is taken care of automatically, and provides type verification for you out of the box.

enum TestStatus < Available, // 0 Ready, // 1 Started, // 2 >class Test < status: TestStatus >var test = new Test(); test.status = TestStatus.Available; // type and spelling is checked for you, // and the sequence ID is automatic 

The values above will be automatically mapped, e.g. «0» for «Available», and you can access them using TestStatus.Available . And Typescript will enforce the type when you pass those around.

If you insist on defining a new type as an array of your custom type

You wanted an array of objects, (not exactly an object with keys «0», «1» and «2»), so let’s define the type of the object, first, then a type of a containing array.

class TestStatus < id: number name: string constructor(id, name)< this.id = id; this.name = name; >> type Statuses = Array; var statuses: Statuses = [ new TestStatus(0, "Available"), new TestStatus(1, "Ready"), new TestStatus(2, "Started") ] 

Источник

How To Define An Array Of Objects In TypeScript?

Tim Mouskhelichvili

Often, a TypeScript developer needs to define an array of objects. Luckily, this is easy to achieve.

In TypeScript, to define an array of objects, you can:

This article will go through those methods and show how to implement them with code examples.

To define an array of objects in TypeScript, a developer must specify the object’s type AND pass it to the array. That way, the array will only be able to hold objects of that specific type.

Solution #1 — Use an existing type or interface

The easiest way to define an array of objects is to define a type or interface that matches the desired structure of one object of the array. Then, you can set the type of the array that holds the objects to array of the created type (or interface).

Let’s see how it works with an example.

typescriptinterface IPerson < name: string; age: number; > const people: IPerson[] = [ < age: 27, name: 'Tim' >, < age: 28, name: 'Bob' > ]

As you can see, we create the IPerson interface, which we use to define the array’s type.

Solution #2 — Use an inline type

If you don’t plan to re-use the object’s type that the array holds, you can define an inline type.

Let’s see how it works with an example.

typescriptconst people: < name: string; age: number; >[] = [ < age: 27, name: 'Tim' >, < age: 28, name: 'Bob' > ]

However, this method can become hard to manage if the object’s type holds a lot of different properties.

The best Web Development course in 2023! 👉 Learn Web Development

Solution #3 — Use the built-in Array type

Another way to define an array of objects in TypeScript is by using the special built-in Array type.

The Array type accepts a generic argument that indicates the structure of the object that the array holds.

Let’s see how it works with an example.

typescriptconst people: Arraystring; age: number; >> = [ < age: 27, name: 'Tim' >, < age: 28, name: 'Bob' > ]

Some developers prefer to use the Array type instead of [] because it is more verbose.

Solution #4 — Use the typeof operator

A different way to define an array of objects involves using the TypeScript typeof operator.

Let’s see how it works with an example.

typescriptconst item1 = < age: 27, name: 'Tim' >; const item2 = < age: 28, name: 'Bob' >; const people: Arraytypeof item2> = [ item1, item2 ];

Using the typeof operator, we can determine the object’s structure and pass it to the Array type.

However, you must have one object constant ready before the array’s initialization.

Final thoughts

As you can see, it is easy to create an array of objects in TypeScript.

We have four different ways of achieving it.

Which one you choose is a question of preference.

typescript array of objects

Here are some other TypeScript tutorials for you to enjoy:

The best Web Development course in 2023! 👉 Learn Web Development

Tim Mouskhelichvili

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js & TypeScript application development. If you need help on a project, please reach out, and let’s work together.

Источник

Читайте также:  Количество символов int python
Оцените статью