0
0
Typescriptprogramming~5 mins

Why object types are needed in Typescript

Choose your learning style9 modes available
Introduction

Object types help us describe the shape of data clearly. They make sure we use the right properties and values in our programs.

When you want to group related information like a person's name and age together.
When you want to check that a function gets an object with the correct properties.
When you want to avoid mistakes by making sure objects have all needed parts.
When you want to understand what kind of data your program expects or returns.
Syntax
Typescript
type Person = {
  name: string;
  age: number;
};

Use type keyword to define a new object type.

Inside curly braces, list property names with their types.

Examples
This defines a Car type with make and year properties.
Typescript
type Car = {
  make: string;
  year: number;
};
This defines a Book type with three properties.
Typescript
type Book = {
  title: string;
  author: string;
  pages: number;
};
Sample Program

This program defines a Person type and a function that uses it. It then creates a user object and greets the user.

Typescript
type Person = {
  name: string;
  age: number;
};

function greet(person: Person) {
  console.log(`Hello, ${person.name}! You are ${person.age} years old.`);
}

const user: Person = { name: "Alice", age: 30 };
greet(user);
OutputSuccess
Important Notes

Object types help catch errors early by checking property names and types.

They make your code easier to read and understand.

Summary

Object types describe the shape of data with named properties.

They help prevent mistakes by enforcing correct property use.

Using object types makes your code clearer and safer.