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 []
}
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.
There is no difference at all. Type[] is the shorthand syntax for an array of Type . Array<Type> is the generic syntax.
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> .
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.
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With