Typescript Foundations / Objects & Interfaces

Object type annotations

πŸ‘‰ Object type annotations tell TypeScript what properties an object should have and what types those properties should be.

βœ… Basic Syntax

let user: { name: string; age: number; isAdmin: boolean; } = { name: "Alice", age: 30, isAdmin: true };

βœ… If you try to add extra fields or use the wrong types, TypeScript will throw errors.

πŸ” Optional Properties

Use ? to mark properties as optional:

let user: { name: string; age?: number } = { name: "Bob" };​

πŸ›  Readonly Properties

Use readonly to prevent changes:

let config: {
  readonly version: string;
  debug: boolean;
} = {
  version: "1.0",
  debug: true
};

// config.version = "2.0"; // ❌ Error: Cannot assign to 'version'

✍ Function Types in Objects

You can annotate functions inside objects like this:

let person: { name: string; greet: (msg: string) => string; } = { name: "Codeveda", greet: (msg) => Hello, ${msg} };

βš™ Using type Alias

To reuse object shapes:

type User = { name: string; age: number; };
let u1: User = { name: "Alice", age: 25 }; 
let u2: User = { name: "Bob", age: 30 };​

🧠 With interface (Alternative to type)

interface Product { 
   id: number; 
   title: string; 
   inStock: boolean; 
} 

const item: Product = { 
   id: 101, 
   title: "Notebook", 
   inStock: true 
};

βœ… interface is great for OOP-style code and can be extended.

πŸ”₯ Index Signature (for dynamic object keys)

let errorBag: { [key: string]: string; } = { email: "Invalid email", username: "Must be at least 3 characters" };

βœ… Summary Table

Feature

Syntax Example

Basic

{ name: string; age: number }

Optional

age?: number

Readonly

readonly id: string

Method

greet: (msg: string) => void

Reuse

type User = { ... } or interface User { ... }

Dynamic keys

[key: string]: string