Returning Values from Decorators
You'll learn when decorators can return values and what those return values actually do.
The Core Idea
Not all decorators need to return anything, but when they do, the return value serves a specific purpose: it replaces the original decorated element. What you return depends on what kind of decorator you're writing. For class decorators, returning a new class constructor replaces the original class. For method, field, and accessor decorators, you can return a function that acts as an initializer — code that runs when the instance or class is being set up.
What Happens When You Return
- Class decorator returns a class: The returned class replaces the original entirely
- Method/field/accessor decorator returns nothing: The original element stays as-is
- Method/field/accessor decorator returns a function: That function becomes an initializer that runs during construction
Think of it like this: when you return something from a decorator, you're saying "actually, use this instead" or "run this extra code when setting up."
The context object you receive in the decorator has an addInitializer method, which is the recommended way to register setup code rather than returning a function directly (though both work).
When Not to Return
If your decorator only needs to observe or modify metadata — like adding a property to the context or logging something — you don't need to return anything. The original decorated value will be used unchanged.
Key Takeaway:
Decorators can return replacement values (for classes) or initializer functions (for members), but only when you need to substitute or augment the original — otherwise, return nothing and let the decorated element stand as-is.