11

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 []

  } 
2
  • Thank you very much for the reply! I tried what you mentioned but it is saying that "orderItem" is referred to as a type but being used as a value. Commented Dec 11, 2017 at 15:55
  • 1
    Now that i see you're trying to create an object literal, i've deleted my comment and added a more relevant answer below Commented Dec 11, 2017 at 16:04

3 Answers 3

13

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Makes a lot more sense now
3

What you want is this:

   this.orders = new Array<orderItem>();

Comments

1

You need to declare it like this:

interface CartState extends Object { orders: OrderItem[] }

class Cart {
  private state: CartState;

  constructor(orders: OrderItem[]) {
    this.state = { orders };
  }
}

Typescript documentation for declaring arrays.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.