簡體   English   中英

如何使用 typescript 在 object 中聲明特定類型的空數組?

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

教程中的代碼

在上面的代碼中,我想聲明一個空的 Ingredient 數組而不是ingredients: [ new Ingredient('Apple', '5')]

在我正在做的教程中,它們沒有顯示空數組的情況。 有沒有辦法做到這一點,還是我總是必須聲明一些值才能讓 angular 知道數組的類型?

您需要聲明您的 state 的類型:

type State = {
  ingredients: Ingredient[];
}

然后將initialState的類型設置為State

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

有很多方法可以做到這一點,試試這個:

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

不確定為什么需要在 object 中定義它,但這會起作用。

這也應該工作

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM