AI Hints
Home›TypeScript Tutorial›Object Types
TypeScript · Lesson 19 of 120

Object Types

Shapes.

⏱ 2 min read▶ Video at 15:16🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Most real data is objects. A bike has a model, a price, and a stock count. An object type describes that shape, the property names, and the type of each.

Object Types
From the video: Object Types
  • Real data is objects
  • Names and types
  • A shape

A bike object

The type after the colon lists each property, and its type. The object must match it exactly. Then we can use every property safely. Run it.

app.tstypescript
const bike: { model: string; price: number; stock: number } = {
  model: "Trail 500",
  price: 849.5,
  stock: 12,
};

console.log(`${bike.model}: £${bike.price}, ${bike.stock} left`);
Output
Trail 500: £849.5, 12 left

A missing property

This object forgets the stock. Run it. TypeScript says the stock property is missing, so the shape stays exactly right.

app.tstypescript
const bike: { model: string; price: number; stock: number } = {
  model: "Trail 500",
  price: 849.5,
};
Output
app.ts line 1: Property 'stock' is missing in type '{ model: string; price: number; }' but required in type '{ model: string; price: number; stock: number; }'.

Summary

Object types list each property and its type, and objects must match. Next, optional properties.

Key takeaways
  • { model: string }
  • Must match
  • No extras
Next up: Optional Properties — maybe there