Skip to content

Decorators and metadata

Relay’s job handlers are classes, and every one of them wraps its methods the same way: retry three times, time the call, register for a webhook event. The first version was a helper, withRetry(this.send). It type-checked, and in production this was undefined inside send, because the helper called the method detached from its object.

A decorator puts the wrapper next to the method, written once, and it can be typed so that misuse does not compile. This lesson covers the decorators TypeScript has implemented since 5.0, which follow the TC39 stage 3 proposal. They are functions with a precise contract, and the checker enforces that contract.

TypeScript has two incompatible features with the same syntax. experimentalDecorators is the legacy one: a method decorator receives (target, key, descriptor). The standard one, used here and enabled by default, receives (value, context). Never mix them in one project. A decorator written for one fails to type-check under the other:

Terminal window
tsc --noEmit --target esnext --experimentalDecorators e.ts
e.ts(2,12): error TS1241: Unable to resolve signature of method decorator when called as an expression.

That output comes from tsc 7 compiling a standard decorator with the legacy flag on. Frameworks written against the legacy flag still need it, so check what a dependency expects before you copy a decorator from its docs. New code should use the standard one. Bun 1.3.10 runs standard decorators natively, and so do the checks in this lesson.

A decorator is a function of (value, context)

Section titled “A decorator is a function of (value, context)”

A decorator is an expression that evaluates to a function. The function receives the thing being decorated and a context object, and it may return a replacement. There are five kinds, and the context type says which:

Kind value Context type Return replaces
class the class ClassDecoratorContext the class
method the function ClassMethodDecoratorContext the function
getter / setter the accessor function ClassGetterDecoratorContext, ClassSetterDecoratorContext the function
field undefined ClassFieldDecoratorContext a function that maps the initial value
accessor { get, set } ClassAccessorDecoratorContext { get?, set?, init? }

Every context has kind, metadata and addInitializer. Member contexts add name, static, private and access. A class context has a name of string | undefined, because a class can be anonymous.

The wrapper must keep the method’s signature. That takes three type parameters: This, the argument tuple, and the return type. Naming them stops the decorator from collapsing every method to (...args: any[]) => any:

function retry(attempts: number) {
return function <This, Args extends unknown[], R>(
target: (this: This, ...args: Args) => Promise<R>,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Promise<R>>
) {
return async function (this: This, ...args: Args): Promise<R> {
let failure: unknown
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
return await target.call(this, ...args)
} catch (error) {
failure = error
}
}
throw failure
}
}
}
class Delivery {
@retry(3)
async send(url: string): Promise<number> {
return url.length
}
// @ts-expect-error: retry needs a method that returns a Promise
@retry(3) parse(raw: string): number {
return raw.length
}
}
export const status: Promise<number> = new Delivery().send("https://example.com")

target.call(this, ...args) is what fixes the withRetry bug: the wrapper is called as delivery.send(...), so this is the delivery, and it forwards it. The Promise<R> in the signature is the rule that makes @retry on parse an error. The checker applies the decorator as a call, retry(3)(parse, context), and a function that returns number is not assignable to a parameter that returns Promise<R>. The rule lives in the decorator’s own type, so a plain signature check enforces it with no custom lint.

A field decorator receives undefined, because a field has no value until an instance exists. It can return a function that maps the initial value to the stored one:

function clamp(max: number) {
return function (_value: undefined, _context: ClassFieldDecoratorContext<unknown, number>) {
return (initial: number): number => Math.min(initial, max)
}
}
class Limits {
@clamp(10) concurrency = 50
}
export const effective: number = new Limits().concurrency

effective is 10 when you run it. The decorator sees the initializer’s result, not the field after later assignments, so limits.concurrency = 50 still stores 50. For ongoing control you need accessor.

accessor is a keyword that declares a field with an automatic private slot behind a generated getter and setter. A decorator on it receives that pair and can wrap either half:

function observed(onChange: (name: string, value: unknown) => void) {
return function <This, V>(
target: ClassAccessorDecoratorTarget<This, V>,
context: ClassAccessorDecoratorContext<This, V>
): ClassAccessorDecoratorResult<This, V> {
return {
set(this: This, value: V) {
onChange(String(context.name), value)
target.set.call(this, value)
}
}
}
}
class Job {
@observed((name, value) => console.log("changed", name, value))
accessor status: "queued" | "running" = "queued"
}
const job = new Job()
job.status = "running"
// @ts-expect-error: "done" is not in the declared union
job.status = "done"

status keeps its literal union type, and assigning "done" is still an error. Getter and setter decorators work like method decorators, with ClassGetterDecoratorContext<This, Value> as the context. Use accessor when the decorator has to observe writes. Use a field decorator when only the initial value matters.

context.addInitializer(fn) registers a function that runs at a well-defined moment. For an instance method, field or accessor it runs per instance, during construction. For a class or a static member it runs once, when the class is defined. That is how a method decorator can bind this without touching the prototype:

function bound<This extends object, Args extends unknown[], V extends (this: This, ...args: Args) => unknown>(
target: V,
context: ClassMethodDecoratorContext<This, V>
) {
const name = context.name
context.addInitializer(function (this: This) {
Reflect.set(this, name, (...args: Args) => target.call(this, ...args))
})
}
class Runner {
id = "runner-1"
@bound run(): string {
return this.id
}
}
const { run } = new Runner()
export const id: string = run()

Destructuring run detaches it from the instance, which is the same shape as passing runner.run as a callback. The initializer defines an own property per instance, so run() works detached and returns "runner-1".

A class decorator receives the class and may return a replacement class, usually a subclass. If it returns nothing, the class stays. A class decorator can also register work for later:

function sealed<C extends abstract new (...args: never[]) => object>(target: C, context: ClassDecoratorContext<C>) {
context.addInitializer(() => {
Object.freeze(target.prototype)
})
}
@sealed
class Settings {
describe(): string {
return "settings"
}
}
export const frozen: boolean = Object.isFrozen(Settings.prototype)

Two phases are easy to confuse: when the decorator expressions run, and when the resulting functions are applied. Running this on Bun 1.3.10 with a log in every step showed that all expressions, such as retry(3), are evaluated first, top to bottom, class decorators before members. The functions are then applied bottom-up for each element, so the decorator written closest to a member runs first. Member decorators are applied before class decorators. Method initializers added by addInitializer run at construction before field initializers, and the constructor body runs last.

declare function a(): (value: unknown, context: ClassMethodDecoratorContext) => void
declare function b(): (value: unknown, context: ClassMethodDecoratorContext) => void
class Order {
@a()
@b()
run(): void {}
}

Here a() is evaluated, then b(). Then b’s function is applied to run, then a’s function receives the result. Decorators compose like function composition, a(b(run)). A decorator that must see the original method goes at the bottom of the stack. Put @retry below @timed when the timing should include all the retries.

TypeScript 5.2 added context.metadata: one plain object per class, shared by all decorators on that class and its members. After the class is defined the engine is supposed to expose it as Class[Symbol.metadata]. A subclass’s metadata object has the parent’s metadata as its prototype.

This is where the runtime matters. I probed Bun 1.3.10: typeof Symbol.metadata is "undefined", context.metadata is an object inside every decorator, and the class never receives [Symbol.metadata], so you cannot read the metadata back. Defining the symbol before the class is declared fixes it, and then A[Symbol.metadata] holds what the decorators wrote. TypeScript’s lib declares Symbol.metadata as read-only, so the polyfill needs a cast:

(Symbol as { metadata: symbol }).metadata ??= Symbol("Symbol.metadata")
function labeled(label: string) {
return function (_value: undefined, context: ClassFieldDecoratorContext): void {
const inherited = Array.isArray(context.metadata.labels) ? context.metadata.labels : []
context.metadata.labels = [...inherited, label]
}
}
class Base {
@labeled("id") id = ""
}
class Child extends Base {
@labeled("attempt") attempt = 0
}
export const baseLabels: unknown = Base[Symbol.metadata]?.labels
export const childLabels: unknown = Child[Symbol.metadata]?.labels

Read the object, copy, then assign. The obvious version, (context.metadata.labels ??= []).push(label), finds the parent’s array through the prototype chain and mutates it. I ran that and got ["x", "y", "z"] as the metadata for the base class, which declares only x and y, because Child’s decorator for z had pushed into the shared array. The version above creates a new own property for each class, so Base ends with ["id"] and Child with ["id", "attempt"].

A decorator hides control flow: a reader of send() can’t see the retry without looking at the line above. Use them for behavior that is the same across many methods and that does not change the method’s meaning: retry, timing, registration. For anything with a business rule, call a function. Decorators also run at class-definition time, which makes them hard to test and impossible to use in the browser playground, which compiles to ESNext and does not downlevel them. That is why this lesson is local.

This one runs on your machine, with Bun. Copy main.starter.ts into the Relay project from M1’s tooling lesson as main.ts, and main.test.ts next to it. The tsconfig there has no experimentalDecorators, which is what you want. Then run bun test.

You implement four decorators: retry, timed (which reports into an injected sink), a field decorator listens that registers a webhook route in context.metadata, and a class decorator handler that snapshots the routes. The starter runs methods once, never reports a failure, shares one routes map between all classes, and accepts decorators on methods that do not return a Promise. The tests include @ts-expect-error lines, so a decorator that is typed too loosely fails bun test through the type checker too: run bunx tsc --noEmit to see those errors.

main.ts
// Relay job handlers are classes. Three decorators remove the boilerplate:
// @retry({ attempts }) re-runs an async method until it succeeds
// @timed(sink, now) reports how long an async method took
// @listens(event) marks a field as the handler for a webhook event
// @handler(source) class decorator that snapshots the routes collected by @listens
//
// Rules:
// - retry({ attempts: 0 }) throws a RangeError whose message contains "attempts".
// - retry calls the method up to `attempts` times, rethrows the LAST error, and passes `this` and the arguments through.
// - retry and timed only compile on methods that return a Promise. A synchronous method is a type error.
// - timed calls sink({ name, ms }) once per call, with the method name, even when the method throws. It reads time only through `now`.
// - listens only compiles on a non-private instance field whose value is a function that accepts EventMap[event].
// - Each class gets its own routes. A subclass inherits its parent's routes and adding to it must not change the parent's.
// - registrationOf(Class) returns { source, routes } where routes maps event name to field name.
// Run: bun test
export type Sink = (entry: { readonly name: string; readonly ms: number }) => void
export interface EventMap {
readonly push: { readonly ref: string }
readonly ping: { readonly zen: string }
readonly release: { readonly tag: string }
}
export interface Registration {
readonly source: string
readonly routes: Readonly<Record<string, string>>
}
export function retry(options: { readonly attempts: number }) {
return function <This, Args extends unknown[], R>(
target: (this: This, ...args: Args) => R,
_context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => R>
) {
return function (this: This, ...args: Args): R {
return target.call(this, ...args)
}
}
}
export function timed(sink: Sink, now: () => number) {
return function <This, Args extends unknown[], R>(
target: (this: This, ...args: Args) => R,
_context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => R>
) {
return function (this: This, ...args: Args): R {
const start = now()
const result = target.call(this, ...args)
sink({ name: "", ms: now() - start })
return result
}
}
}
const routes = new Map<string, string>()
const registry = new WeakMap<object, Registration>()
export function listens<E extends keyof EventMap>(event: E) {
return function <This, Value>(_value: undefined, context: ClassFieldDecoratorContext<This, Value>): void {
routes.set(event, String(context.name))
}
}
export function handler(source: string) {
return function <C extends abstract new (...args: never[]) => object>(target: C, _context: ClassDecoratorContext<C>): void {
registry.set(target, { source, routes: Object.fromEntries(routes) })
}
}
export function registrationOf(target: abstract new (...args: never[]) => object): Registration | undefined {
return registry.get(target)
}
main.test.ts
import { expect, test } from "bun:test"
import { handler, listens, registrationOf, retry, timed, type Sink } from "./main.ts"
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
function flaky(failures: number) {
const state = { calls: 0 }
return {
state,
run(): Promise<string> {
state.calls++
return state.calls <= failures ? Promise.reject(new Error(`attempt ${state.calls}`)) : Promise.resolve("done")
}
}
}
test("retry calls the method again until it succeeds", async () => {
const probe = flaky(2)
class Delivery {
@retry({ attempts: 3 })
async send(to: string): Promise<string> {
return `${await probe.run()}:${to}`
}
}
expect(await new Delivery().send("ops")).toBe("done:ops")
expect(probe.state.calls).toBe(3)
})
test("retry rethrows the last error after the final attempt", async () => {
const probe = flaky(10)
class Delivery {
@retry({ attempts: 3 })
async send(): Promise<string> {
return probe.run()
}
}
const outcome = await new Delivery().send().then(
() => "resolved",
(error: unknown) => (error instanceof Error ? error.message : "not an error")
)
expect(outcome).toBe("attempt 3")
expect(probe.state.calls).toBe(3)
})
test("retry keeps `this` and rejects attempts below one", async () => {
class Counter {
count = 0
@retry({ attempts: 2 })
async bump(): Promise<number> {
this.count++
if (this.count < 2) throw new Error("again")
return this.count
}
}
const counter = new Counter()
expect(await counter.bump()).toBe(2)
expect(() => retry({ attempts: 0 })).toThrow("attempts")
})
test("timed reports the method name and elapsed time, also when the method throws", async () => {
const entries: Array<{ name: string; ms: number }> = []
const sink: Sink = (entry) => entries.push({ ...entry })
let tick = 0
const now = () => (tick += 5)
class Worker {
@timed(sink, now)
async ok(): Promise<number> {
return 1
}
@timed(sink, now)
async broken(): Promise<number> {
throw new Error("boom")
}
}
const worker = new Worker()
expect(await worker.ok()).toBe(1)
const failure = await worker.broken().then(
() => "resolved",
(error: unknown) => (error instanceof Error ? error.message : "not an error")
)
expect(failure).toBe("boom")
expect(entries).toEqual([
{ name: "ok", ms: 5 },
{ name: "broken", ms: 5 }
])
})
test("listens collects routes per class and subclasses do not leak into their parent", () => {
@handler("github")
class Github {
@listens("push") onPush = (event: { ref: string }) => event.ref
@listens("ping") onPing = (event: { zen: string }) => event.zen
}
@handler("github-enterprise")
class Enterprise extends Github {
@listens("release") onRelease = (event: { tag: string }) => event.tag
}
@handler("other")
class Other {}
expect(registrationOf(Github)).toEqual({ source: "github", routes: { push: "onPush", ping: "onPing" } })
expect(registrationOf(Enterprise)).toEqual({
source: "github-enterprise",
routes: { push: "onPush", ping: "onPing", release: "onRelease" }
})
expect(registrationOf(Other)).toEqual({ source: "other", routes: {} })
expect(registrationOf(class {})).toBe(undefined)
})
export function typeChecks() {
class Types {
// @ts-expect-error: retry needs a method that returns a Promise
@retry({ attempts: 2 }) sync(): number {
return 1
}
// @ts-expect-error: timed needs a method that returns a Promise
@timed(() => {}, () => 0) syncTimed(): number {
return 1
}
@listens("push") ok = (event: { ref: string }) => event.ref
// @ts-expect-error: a number is not a handler function
@listens("push") notAFunction = 1
// @ts-expect-error: the push payload has no `zen`
@listens("push") wrongPayload = (event: { zen: string }) => event.zen
// @ts-expect-error: listens decorates fields, not methods
@listens("ping") method(event: { zen: string }) {
return event.zen
}
// @ts-expect-error: private fields are not reachable from outside the class
@listens("ping") #hidden = (event: { zen: string }) => event.zen
}
return Types
}
class Probe {
@retry({ attempts: 2 }) async fetch(id: string): Promise<number> {
return id.length
}
}
export type RetryKeepsTheSignature = Expect<Equal<Probe["fetch"], (id: string) => Promise<number>>>
  • Standard decorators are (value, context) functions. Never mix them with experimentalDecorators.
  • There are five kinds: class, method, getter/setter, field and accessor. The context type tells the checker which kind a decorator accepts.
  • Type decorators with This, an argument tuple and a return type. A constraint such as Promise<R> rejects misuse at compile time.
  • A field decorator maps the initial value. accessor gives you a getter and setter to wrap.
  • addInitializer runs per instance for instance members and once per class otherwise.
  • Expressions evaluate top to bottom, and functions apply bottom-up. The decorator closest to the member sees it first.
  • context.metadata exists everywhere, but Symbol.metadata is missing in Bun 1.3.10. Never mutate inherited metadata: copy, then assign.