Brian Shen

8. Metadata

# Typescript Decorator
Medium
Metadata reflection API (such as Reflect) can be used to organize metadata in a standard way. The use of metadata reflection in decorators is very simple, and it can be seen as attaching some readily available information to a method of a class. Before using it, we must first install the reflect-metadata library with npm i reflect-metadata --save and enable the metadata configuration in tsconfig.json.

Basic usage

et's take a look at how the official TS example uses the reflection API to obtain type information during the design phase of properties. It should be noted that currently there are only three predefined metadata:
  • Type metadata: design:type.
  • Parameter type metadata: design:paramtypes.
  • Return type metadata: design:returntype.

Custom metadata

In addition to using pre-defined metadata like
, we can also customize metadata because we usually use
to customize metadata. For example, we can add a role check to the method of deleting a user, so that only users with the specified role can delete users, such as the administrator role. Please refer to the following code for details.: