Back

TypeScript Object Type

Object types define the shape and property types of objects, improving code robustness by modeling data clearly.

Simple Object Type Definition

let user: { name: string; age: number; isActive: boolean };
user = { name: "Jane", age: 28, isActive: true };

The 'user' object has specified fields with types. TypeScript prevents incorrect usage at compile time.

Optional and Documented Fields

let product: {
  id: number;
  name: string;
  description?: string;
  inStock: boolean;
};
product = {
  id: 1,
  name: "Keyboard",
  inStock: true,
};

Optional fields ('?') allow flexible data, useful in forms and API responses.

Nested Object Types

let order: {
  orderId: string;
  customer: {
    id: number;
    name: string;
  };
  total: number;
};
order = {
  orderId: "ORD123",
  customer: {
    id: 5,
    name: "Ahmet"
  },
  total: 250
};

Objects can nest other objects, enabling complex data modeling with type checks.

Using Object Types in Function Parameters

function createUser(user: { name: string; email: string; role: "admin" | "user" }) {
  console.log(`Yeni kullanıcı: ${user.name} - Rolü: ${user.role}`);
}

Functions typed with objects ensure the passed data matches expected structure.

Defining Object Types with Interfaces

interface BlogPost {
  title: string;
  content: string;
  tags?: string[];
  author: {
    id: number;
    username: string;
  };
}

Interfaces offer reusable and extendable object type definitions, improving maintainability.

Using Interfaces in Functions

function printPost(post: BlogPost) {
  console.log(`${post.title} yazısını yazan: ${post.author.username}`);
}

Interfaces can be used directly for function parameters or components, increasing safety and clarity.

Why Is Type Safety Important with Object Types?

Object types fully utilize TypeScript’s safety, catching errors early and aiding large app maintainability.

Back