skip to content

Why are class decorators a lowering hazard in a TypeScript web build, and how do legacy and standard decorators differ at runtime?

level: seniorimportance: nice to knowfreq 4%

answer

  1. same @ syntax, two meanings
  2. configuration picks the flavour
  3. descriptor versus context object
  4. some fast transformers cannot lower them
  5. metadata needs type information

basics

~20 s

The same @decorator syntax has two incompatible meanings: legacy decorators receive a target, key and descriptor, standard ones a value and a context object. Builds must lower the right flavour, and some fast transformers cannot lower standard decorators yet.

solid answer

~50 s

Decorators are syntax an engine without them cannot parse, so the build must rewrite `@logged` on a class or method into helper calls. The hazard is that two specifications share that syntax. Legacy, experimental decorators, switched on by a TypeScript compiler flag and long relied on by dependency-injection libraries, receive `(target, key, descriptor)`, can decorate constructor parameters and can be paired with type-derived metadata. Standard TC39 decorators receive `(value, context)`, where `context` carries `kind`, `name` and `addInitializer`; field decorators return an initializer, and there are no parameter decorators. A decorator written for one flavour and run under the other gets the wrong arguments and either throws or silently misbehaves. Some native-speed transformers can parse and bundle standard decorators but not lower them, so the `@` syntax reaches the output and an engine without decorators throws a `SyntaxError`; the usual workaround is a slower, plugin-based transpiler run only on files that contain decorators.

code

typescript · 16 lines
typescript
// legacy (experimental) method decorator
function loggedLegacy(target: object, key: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;
  descriptor.value = function (this: unknown, ...args: unknown[]) {
    console.log(`call ${key}`);
    return original.apply(this, args);
  };
}

// standard (TC39) method decorator
function logged(value: Function, context: ClassMethodDecoratorContext) {
  return function (this: unknown, ...args: unknown[]) {
    console.log(`call ${String(context.name)}`);
    return value.apply(this, args);
  };
}

go deeper

for a junior

Recall that decorators are syntax the build must rewrite, and that there are two incompatible flavours selected by configuration rather than by the code.

for a middle

Explain the argument difference, target, key and descriptor against value and context, and what each flavour can decorate, including the missing parameter decorators.

for a senior

Show you would verify the shipped bundle has no leftover decorator syntax, align the flavour across app and libraries, and route decorator files through a transpiler that can lower them.

for a principal

Weigh build speed against migration risk: when a faster toolchain justifies moving off legacy decorators, and who owns the dependency-injection libraries that depend on them.

## Why decorators need lowering at all A **decorator** is a function applied to a class or class element with `@` syntax: ```ts class FareTable { @logged recalculate() { /* ... */ } } ``` An engine that does not implement decorators cannot parse that `@`, so the build must **lower** it: rewrite the class into ordinary code that calls the decorator function with the right arguments at the right time, usually through helper functions. Getting "the right arguments" is where the trouble starts. ## Two specifications, one syntax The `@` syntax has meant two different things over the years, and a file does not say which one it means. The flavour is chosen by **configuration** for the files being compiled. | Aspect | Legacy (experimental) decorators | Standard (TC39) decorators | |---|---|---| | How it is chosen | an opt-in compiler flag, long used by dependency-injection libraries | the default when the legacy flag is off | | Method decorator receives | `(target, key, descriptor)` | `(value, context)` | | How it changes a method | mutates or returns a property descriptor | returns a replacement function | | Field decorator | gets the prototype and key, no initial value | gets `undefined` and may return an initializer | | Parameter decorators | supported | not part of the standard | | Setup hooks | none built in | `context.addInitializer` | | Type-derived metadata | available with a separate compiler option | not supported in that form | Both flavours are "decorators" in documentation and in code review, which is exactly why they get mixed up. ## What goes wrong when the flavours are mixed A mismatch usually does not show up as a build error, because class and method decorators look identical in both flavours; parameter decorators are the exception, since a parser in standard mode rejects them. Everything else shows up at run time: - A **legacy decorator under standard semantics** receives the method itself and a context object instead of a descriptor. Code such as `descriptor.value = wrap(descriptor.value)` reads a property of `undefined` and throws a `TypeError` while the class is being defined. - A **standard decorator under legacy semantics** receives a prototype, a string key and a descriptor. The replacement function it returns is treated as a descriptor rather than as the new method, so in a typical lowering the method silently stays undecorated. - **Parameter decorators**, common in dependency-injection setups, simply have no standard equivalent, so code built on them cannot move to standard semantics unchanged. - **Libraries compiled for one flavour** keep that flavour; your app's setting only controls the files your build compiles. ## Native-speed transformers and the lowering gap **Native-speed transpilers**, written in Go or Rust, are much faster than JavaScript-based ones because they run as compiled code, process files in parallel and avoid a JavaScript plugin pipeline. That speed has a price: - **Lowering support can lag** behind new syntax. Some fast transformers can parse and bundle standard decorators but cannot yet lower them, so the `@` syntax is printed into the output unchanged and any engine without native decorators fails with a `SyntaxError` on parse. - **Plugin breadth is narrower.** A custom syntax-tree transform that a JavaScript-based transpiler runs as a plugin may have no equivalent, or need a native or WebAssembly plugin. - **No type information.** These tools strip TypeScript types file by file and rewrite JSX into function calls, but they do not type-check (that gate is a separate subject). Type-derived decorator metadata, which records a constructor parameter's class from its type annotation, needs types resolved across files, so a per-file transpiler can only approximate it from the annotation text. ## Checking a build that uses decorators 1. **Decide the flavour once**, for the app and for every library it compiles, and record why. 2. **Read your dependencies' compiled output**: legacy decorators show helper calls passing a target, key and descriptor; standard ones pass a context object with `kind` and `name`. 3. **Search the shipped bundle for leftover `@` syntax** on class members after every toolchain change; a successful build does not prove decorators were lowered. 4. **If the fast transformer cannot lower your flavour**, run a slower, plugin-based transpiler only on files containing decorators, and keep the fast path for the rest. 5. **Test class setup in the oldest target browser**, because decorator failures happen when the class is defined, often at module load, not when a method is called.

  • Why is type-derived decorator metadata hard for a per-file transpiler?
    That metadata records design-time types, such as the class of each constructor parameter, so a dependency-injection container can read them at run time. Emitting it correctly needs types resolved across files, which a per-file transpiler does not have; it can approximate common cases from the annotation text, but imported types and aliases may come out wrong. The mechanism exists only alongside legacy decorators.
  • How do you find out which decorator flavour your dependencies expect?
    Read how each library documents its decorators and inspect its compiled output: legacy decorators show helper calls passing a target, key and descriptor, standard ones pass a context object with `kind` and `name`. Then make the app's setting match, because the flavour is chosen by configuration for the files you compile, not by the `@` syntax, and a mismatch surfaces only at run time.

  • Legacy and standard decorators are interchangeable; only the syntax version differs.
  • If the build succeeds, every decorator in the code was lowered.
  • Standard decorators support parameter decorators just like the legacy ones.
  • A native-speed transpiler lowers every syntax a JavaScript-based one does.
  • Type-derived decorator metadata can be emitted exactly without type information.