Skip to content

Decorators and Metadata

How Typeix turns TypeScript decorators into the metadata records that drive injection, routing, schema generation and validation at runtime.

5 min read Source

Typeix has no configuration files, no XML, no registration lists of strings. Everything the framework knows about your application — which class is a controller, which path it answers, which providers a constructor needs, which fields a DTO exposes — is written by decorators and stored as metadata attached to the class. Bootstrapping then reads that metadata back and builds the application from it.

This is why two compiler flags are not optional:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

experimentalDecorators lets you write @Controller() at all. emitDecoratorMetadata is the one people forget: it makes TypeScript emit the types of decorated members into the output, so the runtime can read design:paramtypes and know that a constructor takes a UserService. Without it, every parameter reflects as Object and injection has nothing to resolve. See Requirements.

What a decorator actually does

A TypeScript decorator is a function called by the runtime when the class is defined. It receives the thing it is attached to and attaches data to it with reflect-metadata. The forms and their arguments:

Form Attached to Arguments passed
class the constructor (target)
method the prototype method (target, propertyKey, descriptor)
property the prototype property (target, propertyKey)
parameter the prototype method or constructor (target, propertyKey, paramIndex)

Parameter decorators are the reason injection can be per-argument: the parameter index is what lets resty replace only the seventh constructor argument with a token.

Metadata records

Typeix does not scatter raw Reflect.defineMetadata calls through the codebase. Every decorator is produced by a factory from @typeix/metadata, which generates a namespaced key and records a structured entry:

Field Meaning
metadataKey unique key, e.g. @typeix:parameter:Inject:1:<uuid>
decorator reference to the decorator function itself
type class, method, property or parameter
decoratorType as above, plus mixed for parameter-and-property decorators
args whatever the decorator was called with, e.g. {token: UserService}
propertyKey method name, or constructor
paramIndex parameter position, for parameter decorators
designType value of design:type
designParam value of design:paramtypes
designReturn value of design:returntype

Reading them back is a single call that walks the prototype chain, so a decorator on a base class is visible on the derived class:

import {getAllMetadataForTarget, getClassMetadata} from "@typeix/metadata";
import {Controller} from "@typeix/resty";

getAllMetadataForTarget(UserController);          // every record, derived + inherited
getClassMetadata(Controller, UserController);     // just the @Controller(...) arguments

Two behaviours worth relying on: a (metadataKey, propertyKey) collision is won by the derived class, and getClassMetadata throws if that decorator was never applied anywhere — guard it with isDecorator.

Writing your own decorator

The factories keep the key generation and record shape consistent, so a custom decorator behaves exactly like a built-in one:

import {createMethodDecorator} from "@typeix/metadata";

export function Roles(...roles: string[]) {
  return createMethodDecorator(Roles, {roles});
}
@Controller({path: "/admin"})
class AdminController {
  @Roles("admin", "root")
  @GET()
  dashboard() {
    return "ok";
  }
}

Roles is now discoverable through getAllMetadataForTarget(AdminController) alongside @GET, so an interceptor or a guard can read it without knowing about your decorators in advance.

Decorators must be named

createClassDecorator throws for an anonymous function, because the decorator name is part of the metadata key. Always pass the function itself (createMethodDecorator(Roles, …)), not an arrow that shadows it.

Type erasure — the rule that explains most surprises

emitDecoratorMetadata can only report what JavaScript can see at runtime. That is not the type you wrote:

Declared type Reflected as Consequence
string, number, boolean String, Number, Boolean resolves correctly
a decorated class the class resolves correctly
Date, Buffer Date, Buffer resolves correctly
Promise<User> Promise the User is invisible
User[] Array the item type is invisible
an interface, type alias or union Object nothing to resolve
import type {User} Object nothing to resolve

This single fact explains why @Field(() => [Book]) and @ApiProperty({type: () => PostDto}) take an explicit thunk: the thunk is the only way to state a type that the compiler erased. It also explains why a resolver or a DTO whose property is an interface needs an annotation — reflected metadata says Object, and the framework refuses to guess rather than emitting a wrong schema.

Two rules that prevent real bugs

  • design:* keys are read-only. defineMetadata rejects design:type, design:paramtypes and design:returntype. The arrays belong to reflect-metadata and are shared with every reader of the class, including resty-ws, the OpenAPI generator and the GraphQL schema builder. Any code that needs to substitute a token copies the array first — see getMethodParams in resty.
  • Repeatable decorators are stored as an array. Applying the same decorator twice to one method keeps both records, so a reader must flatten rather than assume one entry.

How the pieces fit

Layer Uses metadata to
@typeix/di read design:paramtypes and @Inject tokens, build constructor arguments
@typeix/resty find @Controller classes and @GET-style methods, compose their paths
@typeix/resty-graphql turn @ObjectType/@Field into a schema
@typeix/resty-swagger turn @ApiProperty/@ApiResponse into OpenAPI
@typeix/resty-ws find @WebSocketController and @Subscribe handlers

Caching and invalidation — a per-class WeakMap validated against a revision counter, plus clearMetadataCache() — are covered in the package reference.