chapter five

5 JavaScript decorators

 

This chapter covers

  • Pros and cons of using decorators
  • Applying decorators
  • Implementing decorators and decorator factories
  • Decorator context, metadata, and access
  • Project configuration with tsc and Vite

Decorators are a programming language feature that can be applied to a piece of code such as a function, class, field, or method to modify its behavior. There’s nothing a decorator can do that can’t be achieved in another way. But decorators reduce boilerplate code. They also make code more declarative, stating goals rather than how to achieve them.

Many programming languages support decorators including C#, Java, JavaScript (and thus TypeScript), Kotlin, Python, Rust, Scala, and Swift.

Some developers avoid using decorators because they introduce a kind of magic — applying a decorator to a programming language construct can change its functionality in a way that’s harder to follow than walking through a sequence of function calls.

So, why does a book on web components contain an entire chapter on a JavaScript feature: decorators? Several of the web component libraries discussed later provide decorators and promote their use. Having this foundational knowledge now will make future lessons easier to understand.

Note

The projects for many of the examples in this chapter, found in the ch05 directory of the book code repository, use Vite or the TypeScript compiler tsc. Details on creating projects that use those are provided in the 5.11 section.

5.1 Decorator proposals

5.2 Decorators in JavaScript

5.3 A first decorator

5.4 accessor keyword

5.5 Decorator context

5.6 Decorator examples

5.6.1 logField decorator

5.6.2 logAccess decorator

5.6.3 timeMethod decorator

5.6.4 countInstances decorator

5.7 Decorator factories

5.7.1 rangeValidation decorator factory

5.7.2 customElement decorator factory

5.7.3 on decorator factory

5.8 Applying multiple decorators

5.9 Context metadata

5.9.1 Context metadata example