Course contentsShow
← TypeScript
Lesson 1085 of 1,79625. The this TypeFree lesson

Factory Function Pattern

Applying ThisType<T> in factory functions that create objects with typed this context in methods.

Factory Function Pattern with ThisType<T>

What you'll learn: How to use ThisType<T> to enforce typed this inside factory functions that create objects with methods.

The Problem Factory Functions Face

In JavaScript, factory functions are popular alternatives to classes — they return new objects without using new. But when these factories create objects with methods, TypeScript struggles to know what this means inside those methods. Without help, this becomes any, losing type safety entirely.

function createCounter() {
  return {
    count: 0,
    increment() {
      this.count++; // What is 'this' here?
    }
  };
}

What ThisType<T> Does

ThisType<T> is a marker utility type that tells TypeScript: "Inside this object, this should be typed as T." It doesn't change runtime behavior — it's purely a compile-time hint.

Think of it as labeling a toolbox: the tools don't change, but everyone now knows what they're working with.

Basic Factory Pattern with ThisType

type Counter = {
  count: number;
  increment(): void;
  reset(): void;
};

function createCounter(): Counter {
  const methods: ThisType<Counter> = {
    increment() {
      this.count++; // ✓ this is Counter
    },
    reset() {
      this.count = 0; // ✓ this is Counter
    }
  };

  return {
    count: 0,
    ...methods
  };
}

Now this inside increment and reset is correctly typed as Counter, giving you autocomplete and error checking.

Real-World Example: Object with State and Methods

type StateManager = {
  data: Record<string, unknown>;
  get(key: string): unknown;
  set(key: string, value: unknown): void;
};

function createStateManager(): StateManager {
  const api: ThisType<StateManager> = {
    get(key) {
      return this.data[key]; // ✓ this.data is typed
    },
    set(key, value) {
      this.data[key] = value; // ✓ safe property access
    }
  };

  return {
    data: {},
    ...api
  };
}

Key Takeaway: Use ThisType<T> in factory functions to give methods a typed this context, maintaining type safety without using classes.