TypeScript Object Types

TypeScript tutorial

🧱 TypeScript Object Types

In TypeScript, Object Types define the structure (shape) of an object—
what properties it has and what types those properties must be.

1️⃣ Basic Object Type

let user: { name: string; age: number } = {
name: "Sanjit",
age: 25
};

❌ Error if property is missing or wrong type.

2️⃣ Optional Properties (?)

Use ? when a property may or may not exist.

let student: {
id: number;
name: string;
email?: string;
} = {
id: 1,
name: "Rahul"
};

3️⃣ Readonly Properties

Cannot be changed after initialization.

let product: {
readonly id: number;
name: string;
price: number;
} = {
id: 101,
name: "Laptop",
price: 50000
};

❌ Not allowed:

product.id = 102;

4️⃣ Object Type with Methods

let person: {
name: string;
greet: () => void;
} = {
name: "Amit",
greet() {
console.log("Hello!");
}
};

5️⃣ Nested Object Types

let employee: {
id: number;
profile: {
name: string;
department: string;
};
} = {
id: 1,
profile: {
name: "Sanjit",
department: "IT"
}
};

6️⃣ Index Signatures (Dynamic Keys)

Used when property names are unknown.

let scores: {
[subject: string]: number;
} = {
math: 90,
science: 85
};

7️⃣ Object Type with Arrays

let company: {
name: string;
employees: { id: number; name: string }[];
} = {
name: "TechCorp",
employees: [
{ id: 1, name: "Amit" },
{ id: 2, name: "Rahul" }
]
};

8️⃣ Type Aliases vs Object Types (Preview)

Instead of repeating object types:

type User = {
id: number;
name: string;
};
let admin: User = { id: 1, name: “Sanjit” };

(We’ll cover Type Aliases in detail next.)

🔑 Object Types Summary

FeatureSyntax
Basic Object{ name: string }
Optionalproperty?: type
Readonlyreadonly property
Nested{ a: { b: type } }
Dynamic Keys[key: string]: type
With Methodsmethod(): returnType

⭐ Best Practices

✔ Use object types to define data shape
✔ Use optional properties wisely
✔ Prefer readonly where possible
✔ Use type aliases for reuse

You may also like...