简体   繁体   中英

How to declare a specific type of empty array inside a object using typescript?

教程中的代码

In the above code, I want to declare an empty Ingredient array instead of ingredients: [ new Ingredient('Apple', '5')]

In the tutorial that I am doing, they don't show the case of the empty array. Is there a way to do it or do I always have to declare some values to let the angular know the type of the array?

You need to declare the type of your state:

type State = {
  ingredients: Ingredient[];
}

and then set the type of initialState to State :

const initialState: State = {
  ingredients: [],
}

There are many ways to do it really, try this:

let ingredients: Ingredient[] = [];
const initialState = {
    ingredients: ingredients
}

Not sure why you need to define it inside an object, but this will work.

This should also work

    const initialState = {
      ingredients: new Array<Ingredient>()
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM