Skip to content

Instantly share code, notes, and snippets.

@coltenkrauter
Last active May 26, 2024 02:16
Show Gist options
  • Select an option

  • Save coltenkrauter/818cb6f27b471c645c2305acf8d0c6a5 to your computer and use it in GitHub Desktop.

Select an option

Save coltenkrauter/818cb6f27b471c645c2305acf8d0c6a5 to your computer and use it in GitHub Desktop.
10 Ways to Use TypeScript Interfaces

10 Ways to Use TypeScript Interfaces

Table of Contents

  1. Basic Object Shape
  2. Optional Properties
  3. Readonly Properties
  4. Index Signatures
  5. Extending Interfaces
  6. Function Types
  7. Hybrid Types
  8. Class Types
  9. Intersection Types
  10. Implementing Interfaces in Classes
  11. Types Vs Interfaces

1. Basic Object Shape

Defines the shape of an object, specifying the properties and their types.

interface OfficeEmployee {
  name: string;
  position: string;
}

const michaelScott: OfficeEmployee = {
  name: "Michael Scott",
  position: "Regional Manager"
};

2. Optional Properties

Allows properties to be optional by adding a question mark ?.

interface OfficeEmployee {
  name: string;
  position?: string;
}

const jimHalpert: OfficeEmployee = {
  name: "Jim Halpert"
};

3. Readonly Properties

Ensures properties cannot be changed after initialization.

interface DundieAward {
  readonly id: number;
  title: string;
}

const bestBossAward: DundieAward = {
  id: 1,
  title: "Best Boss"
};

// bestBossAward.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.

4. Index Signatures

Defines properties with dynamic keys and their types.

interface ScrantonBranch {
  [employeeName: string]: string;
}

const scrantonEmployees: ScrantonBranch = {
  "Michael Scott": "Regional Manager",
  "Dwight Schrute": "Assistant Regional Manager"
};

5. Extending Interfaces

Allows interfaces to inherit properties from other interfaces.

interface Employee {
  name: string;
}

interface Salesperson extends Employee {
  salesRegion: string;
}

const phyllisVance: Salesperson = {
  name: "Phyllis Vance",
  salesRegion: "Northeast"
};

6. Function Types

Describes the types for functions, including parameters and return types.

interface MeetingScheduler {
  (time: string, topic: string): string;
}

const scheduleMeeting: MeetingScheduler = (time: string, topic: string) => {
  return `Meeting scheduled at ${time} about ${topic}`;
};

7. Hybrid Types

Interfaces can describe objects that are both functions and have properties.

interface Prank {
  (target: string): string;
  prankName: string;
  execute(): void;
}

const jimPrank: Prank = (target: string) => {
  return `Pranking ${target}`;
};

jimPrank.prankName = "Stapler in Jello";
jimPrank.execute = () => {
  console.log("Executing prank: Stapler in Jello");
};

8. Class Types

Defines the shape of an instance of a class.

interface Manager {
  department: string;
  manage(): void;
}

class OfficeManager implements Manager {
  department: string;

  constructor(department: string) {
    this.department = department;
  }

  manage() {
    console.log(`Managing the ${this.department} department`);
  }
}

9. Intersection Types

Combines multiple types into one.

interface Event {
  title: string;
  date: string;
}

interface Party {
  theme: string;
}

type OfficeParty = Event & Party;

const dundieAwards: OfficeParty = {
  title: "Dundie Awards",
  date: "Friday, 7 PM",
  theme: "Awards Night"
};

10. Implementing Interfaces in Classes

Implements an interface in a class to ensure the class adheres to the interface structure.

interface Volunteer {
  name: string;
  task(): void;
}

class OfficeVolunteer implements Volunteer {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  task() {
    console.log(`${this.name} is organizing the charity event`);
  }
}

const pamBeesly = new OfficeVolunteer("Pam Beesly");
pamBeesly.task(); // Pam Beesly is organizing the charity event

Types Vs Interfaces

Types and interfaces in TypeScript serve different purposes and have distinct use cases. Interfaces are primarily used to define the shape of objects or classes and support declaration merging, making them ideal for object-oriented programming and extending third-party libraries. Types, on the other hand, are more versatile, capable of representing primitives, unions, intersections, and complex type constructions. They are suitable for creating complex types, utility types, and working with a broader range of type definitions. Use interfaces for defining object structures and when declaration merging is needed, and use types for complex type definitions, working with primitives, and creating utility types.

Use Interfaces:

  • Object Shape Definition:

    • Use interfaces when defining the structure of an object or a class. Interfaces are specifically designed for this purpose and are more readable and conventional in the context of object-oriented programming.
  • Declaration Merging:

    • Interfaces can be merged, meaning you can declare the same interface multiple times, and TypeScript will combine them into a single interface definition. This is useful for extending the capabilities of third-party libraries or organizing your code.

Use Types:

  • Complex Type Definitions:

    • Use types when you need to define more complex types that go beyond the shape of an object. This includes union types, intersection types, and tuples.
  • Working with Primitives and Non-Object Types:

    • Types are more versatile than interfaces as they can represent any kind of type, including primitives (string, number, boolean), unions, and intersections. This makes them suitable for a broader range of type definitions.
  • Utility Types and Mapped Types:

    • Use types when working with utility types or mapped types to transform existing types into new ones.

This Gist was created with the assistance of ChatGPT.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment