Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of custom types typescript

I have an interface with the following:

interface orderItem {
  symbol: string,
  side: string,
  price: number
  quantity: number
}

I want to create an array "orders" consisting of "orderItems" in my constructor.

However, orders : [orderItem] doesn't seem to be doing the trick. Does anyone know how I can proceed?

Here is what I am trying to do in my constructor:

   this.state = {
      orders: orderItem []

  } 
like image 216
blazerix Avatar asked Dec 11 '17 15:12

blazerix


People also ask

How do you declare an array of types in TypeScript?

In TypeScript, an array is an ordered list of values. An array can store a mixed type of values. To declare an array of a specific type, you use the let arr: type[] syntax.

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.

How do you give an array a type?

To create an array type you can use Array<Type> type where Type is the type of elements in the array. For example, to create a type for an array of numbers you use Array<number> . You can put any type within Array<Type> .

How do you declare an array of objects in TypeScript interface?

TypeScript Arrays are themselves a data type just like a string, Boolean, and number, we know that there are a lot of ways to declare the arrays in TypeScript. One of which is Array of Objects, in TypeScript, the user can define an array of objects by placing brackets after the interface.


1 Answers

Since you're doing an object literal, the colon is used to divide the key from the value (ie, it has its normal javascript meaning, not its typescript meaning). As a result, trying to set the type the way you're doing is causing an error.

There are a few ways you could do what you want. You could set the type using the as keyword:

this.state = {
    orders: undefined as orderItem[]
};

or with an empty array:

this.state = {
    orders: [] as orderItem[]
};

Or you could create something ahead of time, and then insert that into the object:

let myOrders: orderItem[] = [];
this.state = {
     orders: myOrders
};

Or you could have a separate interface for the state and use that:

interface myState {
    orders: orderItem[]
}

class myClass {
    private state: myState;
    constructor () {
        this.state = {
            orders: undefined
        }
    }
}
like image 108
Nicholas Tower Avatar answered Oct 05 '22 23:10

Nicholas Tower