Skip to Content
GuidesforwardRef

forwardRef

Use forwardRef to reference a class that is defined after the class that depends on it.

The Problem

TypeScript/JavaScript evaluates code top-to-bottom. If class A depends on class B, but B is defined after A, the dependency will be undefined:

// ❌ This won't work - Father is undefined when Person is evaluated class Person { constructor(@Inject(Father) readonly father: Father) {} } class Father extends Person {}

The Solution

Wrap the dependency in forwardRef:

// ✅ This works class Person { constructor( @SkipSelf() @Optional(forwardRef(() => Father)) readonly father: Father ) {} } class Father extends Person { changeDiaper(): void {} }

This is a JavaScript/TypeScript behavior, not specific to redi. The same pattern exists in Angular and other DI frameworks.

When to Use

  • Circular class references
  • Classes defined after their dependents
  • Mutual dependencies between files
Last updated on