網站搜尋

陣列 - Typescript:如何宣告字典列表的類型?


我想要宣告一個字典列表,其中鍵是 string,值是 number。

我該如何修改下面的程式碼,使 count 宣告為字串列表。

const dict: string[] = [];

答案#1

字典,其中鍵是字串,值是數字。

這是一個 Record 類型。在這種情況下:

Record<string, number>

或者索引簽名也可以使用:

{ [myKey: string]: number }

然後只需在其中任何一個的末尾添加 [],即可將其變成這些對象的數組。

const dict: Record<string, number>[] = [
  { a: 123, b: 456 },
  { c: 789 },
]