如何定义对象数组? [英] How can I define an array of objects?
问题描述
我正在用 TypeScript 创建一个对象数组:
I am creating an array of objects in TypeScript:
userTestStatus xxxx = {
"0": { "id": 0, "name": "Available" },
"1": { "id": 1, "name": "Ready" },
"2": { "id": 2, "name": "Started" }
};
谁能告诉我如何正确声明它的类型?是否可以内联或者我需要两个定义?
Can someone tell me how I could declare its type correctly? Is it possible to do inline or would I need two definitions?
我希望用类型声明替换 xxx
,这样以后如果我使用了类似 userTestStatus[3].nammme
的东西,TypeScript 会提醒我错误.
I'm looking to replace the xxx
with a type declaration, so that later on TypeScript would alert me if I used something like userTestStatus[3].nammme
by mistake.
推荐答案
最好使用 本机数组 而不是具有类似数字属性的对象字面量,因此编号(以及许多其他数组函数)可以现成.
You are better off using a native array instead of an object literal with number-like properties, so that numbering (as well as numerous other array functions) are taken care of off-the-shelf.
您在此处寻找的是数组的内联 interface 定义定义该数组中的每个元素,无论是最初存在还是稍后引入:
What you are looking for here is an inline interface definition for your array that defines every element in that array, whether initially present or introduced later:
let userTestStatus: { id: number, name: string }[] = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]
如果您立即使用值初始化数组,则不需要显式类型定义;TypeScript 可以从初始赋值中自动推断出大多数元素类型:
If you are initializing your array with values right away, the explicit type definition is not a necessity; TypeScript can automatically infer most element types from the initial assignment:
let userTestStatus = [
{ "id": 0, "name": "Available" },
...
];
userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]
这篇关于如何定义对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!