Typescript Foundations / Objects & Interfaces

Interfaces: defining shape of objects

An interface in TypeScript defines the structure of an object — what properties it should have and what their types should be.

Think of it like a blueprint for objects.


✅ Basic Syntax

interface User {
  name: string;
  age: number;
  isAdmin: boolean;
}

You can then use this interface as a type:

const user: User = {
  name: "Tisha",
  age: 21,
  isAdmin: true
};

🧠 Optional Properties

Use ? to mark a property as optional:

interface User {
  name: string;
  age?: number; // optional
}

🔐 Readonly Properties

Use readonly to make a property immutable:

interface Config {
  readonly version: string;
  debug: boolean;
}
const settings: Config = {
  version: "1.0",
  debug: true
};

settings.version = "2.0"; // ❌ Error

🛠 Methods in Interfaces

interface Person {
  name: string;
  greet(msg: string): string;
}

const person: Person = {
  name: "Alice",
  greet: (msg) => `Hello ${msg}`
};

console.log(person.name) //Alice
console.log(person.greet("Codeveda")) //Hello Codeveda

🔁 Extending Interfaces (Inheritance)

Interfaces can extend other interfaces:

interface Animal {
  name: string;
}
interface Dog extends Animal {
  breed: string;
}
const pet: Dog = {
  name: "Tommy",
  breed: "Labrador"
};

console.log(pet.name) //Tommy
console.log(pet.breed) //Labrador

✨ Interface vs Type (Quick Recap)

Feature

interface

type

Object structure

✅

✅

Unions/Intersections

❌

✅

Can be extended

✅ (extends)

✅ (&)

Declaration merging

✅

❌

Primitives, arrays, etc.

❌

✅


🔥 Combined Example


📌 Summary

Concept

Syntax

Basic interface

interface User { name: string; }

Optional

age?: number

Readonly

readonly id: number

Method

greet(msg: string): string

Extend

interface Admin extends User


✅ Interfaces are clean, extendable, and perfect for defining object models.

They also integrate well with OOP patterns, React props, and API responses.