Course contentsShow
← JavaScript
Lesson 2086 of 2,72343. DecoratorsFree lesson

When Decorators Cannot Be Used

Identify contexts where decorators are prohibited: function declarations, object literals, and parameter decorators.

When Decorators Cannot Be Used

You'll learn: Where JavaScript decorators are forbidden and cannot be applied, keeping you from confusing syntax errors.

The Concept

While decorators are powerful tools for enhancing classes, they don't work everywhere. The decorators proposal explicitly prohibits them in three important contexts:

  1. Function Declarations – You cannot decorate standalone function declarations. Decorators only work on class members, not top-level functions.

  2. Object Literals – Methods or properties inside plain object literals cannot use decorators. Decorators are exclusively for class syntax.

  3. Parameter Decorators – Unlike TypeScript's experimental decorators, the Stage 3 proposal does not support decorating individual function parameters.

Why These Restrictions?

Think of decorators like special tools designed for assembly lines (classes). They're built to modify workstations (class members) on that line. They simply weren't designed to work on standalone items (functions) or informal workbenches (object literals). Parameter decorators were deliberately left out of the proposal to keep the specification simpler and more focused.

What This Means in Practice

// ❌ Cannot decorate function declarations
@logged
function myFunction() {}

// ❌ Cannot decorate object literal methods
const obj = {
  @logged
  method() {}
};

// ❌ No parameter decorators
class MyClass {
  method(@validate param) {} // Not supported
}

// ✅ Only class members work
class MyClass {
  @logged
  method() {}
}

If you need decorator-like behavior for functions or object methods, you'll need to wrap them manually or use higher-order functions instead.

Key Takeaway: Decorators are class-only syntax—they cannot be applied to function declarations, object literal members, or function parameters in the Stage 3 proposal.