codez.guru

Typing Objects with Inline Annotations

You can annotate objects directly:

const user: {
  name: string;
  age: number;
} = {
  name: "Alex",
  age: 30,
};

This works but becomes hard to reuse. Enter interfaces.


Using Interfaces

Use interface to define reusable object shapes:

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

const user: User = {
  name: "Lior",
  age: 28,
};

Interfaces help maintain consistency across components, APIs, and models.


Optional and Readonly Properties

Optional ?

interface Product {
  id: number;
  description?: string;
}

This allows description to be omitted.

Readonly

interface Config {
  readonly apiKey: string;
}

Trying to change apiKey after initialization will throw an error during development.


Extending Interfaces

Interfaces can extend each other like classes:

interface Person {
  name: string;
}

interface Employee extends Person {
  role: string;
}

const e: Employee = {
  name: "Dana",
  role: "Developer",
};

This promotes DRY code and composability.


Type Aliases vs Interfaces for Objects

You can also use type:

type Car = {
  brand: string;
  year: number;
};

> Prefer interface when defining object shapes.
> Prefer type when composing unions, primitives, functions, etc.

Interfaces can be merged (declaration merging), while types are static.


Summary

  • Use interface to define structured and reusable object types
  • Use ? for optional and readonly to prevent mutation
  • Extend interfaces to create hierarchical data models
  • Know when to use type vs interface — both are powerful tools

Next up: arrays, tuples, and how to create safe, structured collections in TypeScript.