TS Object Types

TypeScript Object Types

Objects are the most common way to group related data in JavaScript and TypeScript.

In TypeScript, you can define the exact shape an object must take.

You do this by specifying the type of every single property inside the object.

This prevents you from referencing properties that do not actually exist.


1. Defining Object Types

To define an object's type, you simply write an object literal with types.

Instead of values, you write the expected type for each corresponding key.

This syntax is clean, intuitive, and highly readable for other developers.

Basic Object Example:

let car: { make: string; year: number } = {
  make: "Toyota",
  year: 2022
};

console.log(car.make);


2. Optional Properties

Sometimes, an object might have a property that is not strictly required.

You can make a property optional by adding a ? right after the property name.

This tells TypeScript that it is perfectly fine if this property is completely missing.

Optional Property Example:

let user: { name: string; age?: number } = {
  name: "Akash"
};

// We didn't provide 'age', and TypeScript is completely happy! console.log(user.name);


3. SEO and Scalability

Strongly typing your data objects is the secret to building highly scalable APIs.

When your data structures are predictable, front-end rendering becomes much faster.

A fast, bug-free website directly boosts your search engine rankings and SEO scores.

Complex Object Example:

let article: { title: string; views: number; isPublished: boolean } = {
  title: "Learn TypeScript",
  views: 1500,
  isPublished: true
};

console.log("Article:", article.title, "| Views:", article.views);


Exercise

?

How do you make an object property optional in TypeScript?


4. Final Thoughts

Typing objects inline is great for very small scripts and simple data.

However, for larger applications, we use Interfaces and Aliases.

We will learn about those shortly, right after exploring Enums!