TypeScript Object Types and Interfaces
Most data in real apps is made of objects. TypeScript lets you describe exactly which properties an object has and their types.
Object Types
Write the properties and their types inside curly brackets:
Example
const student: { name: string; rollNo: number; city: string } = {
name: "Ali",
rollNo: 117,
city: "Karachi"
};
console.log(student.name);
// student.age; // Error: Property 'age' does not exist on type ...Ali
Writing the shape inline every time gets long, so we give it a name.
Type Aliases
The type keyword gives a name to any type:
Example
type Product = {
name: string;
price: number;
inStock: boolean;
};
const fan: Product = { name: "Ceiling Fan", price: 8500, inStock: true };
const iron: Product = { name: "Dry Iron", price: 3200, inStock: false };
function label(p: Product): string {
return `${p.name}: Rs ${p.price}${p.inStock ? "" : " (sold out)"}`;
}
console.log(label(fan));
console.log(label(iron));Ceiling Fan: Rs 8500 Dry Iron: Rs 3200 (sold out)
If a property is missing or has the wrong type, TypeScript shows an error.
Interfaces
An interface is another way to name an object shape. For objects, it works almost the same as a type alias:
Example
interface Student {
name: string;
course: string;
marks: number;
}
const ayesha: Student = { name: "Ayesha", course: "Web Development", marks: 93 };
console.log(`${ayesha.name} (${ayesha.course}) scored ${ayesha.marks}`);Ayesha (Web Development) scored 93
Optional and Readonly Properties
?makes a property optionalreadonlymeans it can be set when the object is created, but never changed
Example
interface User {
readonly id: number;
name: string;
phone?: string;
}
const user: User = { id: 1, name: "Bilal" }; // phone can be left out
user.name = "Bilal Ahmed"; // fine
// user.id = 2; // Error: Cannot assign to 'id' because it is a read-only property
console.log(user.phone ?? "No phone number");No phone number
Extending Interfaces
One interface can extend another and add more properties:
Example
interface Person {
name: string;
city: string;
}
interface Teacher extends Person {
subject: string;
}
const sir: Teacher = { name: "Imran", city: "Karachi", subject: "JavaScript" };
console.log(`${sir.name} teaches ${sir.subject}`);Imran teaches JavaScript
With type aliases you get the same result with & (an intersection type): type Teacher = Person & { subject: string };
Methods in Object Types
Objects can also have functions as properties:
Example
interface Cart {
items: number[];
total(): number;
}
const cart: Cart = {
items: [500, 1200, 300],
total() {
return this.items.reduce((a, b) => a + b, 0);
}
};
console.log(cart.total());2000
type or interface?
type | interface | |
|---|---|---|
| Object shapes | Yes | Yes |
Unions like "a" OR "b" | Yes | No |
| Extending | With & | With extends |
| Can be declared twice and merged | No | Yes |
Both are fine for objects. A common rule: use interface for object shapes and type for everything else, and stay consistent in one project.
Index signatures describe objects with any number of keys: { [subject: string]: number } fits { maths: 90, urdu: 85 }. The Record<string, number> type means the same.
Exercise
Exercise
In interface Order { id: number; note?: string }, which object is valid?
