Typing Objects and Arrays of Objects
Svep för att visa menyn
In backend development, you often work with structured data such as users, products, or orders. TypeScript helps you define the shape of this data using object types.
Typing Objects
You can define the structure of an object directly:
let user: { name: string; age: number } = {
name: "Alice",
age: 30,
};
This ensures the object always contains the required fields with the correct types.
Missing or Incorrect Properties
If a property is missing or has the wrong type, TypeScript will show an error:
let user: { name: string; age: number } = {
name: "Alice",
// age is missing → Error
};
Arrays of Objects
You can also define arrays that contain structured objects:
let users: { name: string; age: number }[] = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
];
This is very common in backend development when working with lists of data.
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 1. Kapitel 5
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Avsnitt 1. Kapitel 5