Decorator metadata
- TypeScript course
- Expert
- Lesson 21/35
- 4 min
Learn type metadata with emitDecoratorMetadata.
What is emitDecoratorMetadata?
emitDecoratorMetadata: true carries the type information of decorated elements to runtime. Each decorator call gets a metadata parameter holding the target's type. This is required for dependency injection libraries (e.g. NestJS, TypeDI) to work.
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}experimentalDecorators must also be enabled.
Metadata format
With emitDecoratorMetadata on, TypeScript adds three metadata keys to the decorator call: design:type (property type), design:paramtypes (parameter types), and design:returntype (return type). This data is stored via Reflect.metadata.
// after compilation:
// __decorate([
// Reflect.metadata("design:type", Function),
// Reflect.metadata("design:paramtypes", [String])
// ], ...)This is why the reflect-metadata polyfill is required.
Practice Produce the metadata keys
Write a buildMetadataKeys function that returns the metadata key array based on hasType, hasParams, and hasReturn parameters. Print the result of buildMetadataKeys(true, true, false) joined with commas.
Starter code
// buildMetadataKeys: metadata anahtar dizisini üretir
// özellik türü bayrağı açık ise design:type ekle
// parametre türü bayrağı açık ise design:paramtypes ekle
// dönüş türü bayrağı açık ise design:returntype ekle
// (true, true, false) için diziyi join ile yazdırSample solution
function buildMetadataKeys(hasType: boolean, hasParams: boolean, hasReturn: boolean): string[] {
const keys: string[] = [];
if (hasType) keys.push("design:type");
if (hasParams) keys.push("design:paramtypes");
if (hasReturn) keys.push("design:returntype");
return keys;
}
console.log(buildMetadataKeys(true, true, false).join(", "));Expected output
design:type, design:paramtypes
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which libraries specifically require emitDecoratorMetadata?
- Dependency injection libraries Correct answer
- State management libraries
- Testing libraries
- Debugging libraries
Explanation: Dependency injection libraries (such as NestJS, TypeDI) rely on decorator metadata; debugging, state management, and testing libraries do not require decorator metadata.
2 Enable the metadata flag
{
"compilerOptions": {
"experimentalDecorators": true,
"____": true
}
}
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
Explanation: To carry type metadata to runtime use emitDecoratorMetadata; emitMetadata, decoratorMetadata, and metadata are not valid option names.
3 Decorator metadata parts
| Term | Meaning |
|---|---|
emitDecoratorMetadata |
carries type info to runtime |
experimentalDecorators |
enables decorators |
design:type |
property type metadata |
reflect-metadata |
polyfill that stores metadata |