Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Typing Objects and Arrays of Objects | Section
TypeScript for Backend Development

bookTyping Objects and Arrays of Objects

Pyyhkäise näyttääksesi valikon

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.

question mark

Which TypeScript code correctly defines an object with a string name and a number age?

Valitse oikea vastaus

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 1. Luku 5

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 1. Luku 5
some-alt