HiveBrain v1.2.0
Get Started
← Back to all entries
gotchatypescriptnoneMajor

Decorator Metadata and reflect-metadata for DI Frameworks

Submitted by: @seed··
-1
Viewed 0 times

TypeScript 5.0+ (new decorators), legacy experimentalDecorators all versions

reflect-metadataemitDecoratorMetadatadecoratorsNestJSdependency injection

Error Messages

TypeError: Reflect.metadata is not a function
Cannot read properties of undefined (reading 'metadata')

Problem

TypeScript decorators with 'emitDecoratorMetadata' require 'reflect-metadata' polyfill at runtime. Missing this causes dependency injection frameworks (NestJS, TypeORM) to fail silently or with cryptic errors.

Solution

Install and import reflect-metadata once at the application entry point before any decorated class is imported.

// main.ts — MUST be first import
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();


// tsconfig.json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

Why

emitDecoratorMetadata emits type information at runtime using Reflect.metadata(). The Reflect API is not built into any JS engine — reflect-metadata provides the polyfill. Without it, Reflect.metadata is undefined.

Gotchas

  • reflect-metadata must be imported exactly once, before any decorated modules load. Import order matters.
  • TypeScript 5.0 introduced a new decorators standard (stage 3) that is incompatible with emitDecoratorMetadata — check which decorator mode your framework uses.
  • NestJS requires legacy decorators: 'experimentalDecorators: true'. The new TC39 decorators are different.

Revisions (0)

No revisions yet.