How can I define an array of objects?
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?
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.
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 [...]
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 [...]
What you have above is an object, not an array.
To make an array use [
& ]
to surround your objects.
userTestStatus = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
Aside from that TypeScript is a superset of JavaScript so whatever is valid JavaScript will be valid TypeScript so no other changes are needed.
Feedback clarification from OP... in need of a definition for the model posted
You can use the types defined here to represent your object model:
type MyType = {
id: number;
name: string;
}
type MyGroupType = {
[key:string]: MyType;
}
var obj: MyGroupType = {
"0": { "id": 0, "name": "Available" },
"1": { "id": 1, "name": "Ready" },
"2": { "id": 2, "name": "Started" }
};
// or if you make it an array
var arr: MyType[] = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
Some tslint
rules are disabling use of [], example message: Array type using 'T[]' is forbidden for non-simple types. Use 'Array<T>' instead.
Then you would write it like:
var userTestStatus: Array<{ id: number, name: string }> = Array(
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
);