TypeScript Tutorial menu

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

typescript
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 ...
Output
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

typescript
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));
Output
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

typescript
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}`);
Output
Ayesha (Web Development) scored 93

Optional and Readonly Properties

  • ? makes a property optional
  • readonly means it can be set when the object is created, but never changed

Example

typescript
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");
Output
No phone number

Extending Interfaces

One interface can extend another and add more properties:

Example

typescript
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}`);
Output
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

typescript
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());
Output
2000

type or interface?

typeinterface
Object shapesYesYes
Unions like "a" OR "b"YesNo
ExtendingWith &With extends
Can be declared twice and mergedNoYes

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?

Learn TypeScript with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp