ES-модуль типизированной обертки для Metadata Reflection API
npm install @e22m4u/ts-reflector
Для использования данного модуля требуется поддержка вашим проектом возможности загрузки модулей стандарта ECMAScript. Рекомендуемый способ настройки TypeScript проекта для работы с ESM заключается в выполнении шагов указанных ниже.
- добавить
"type": "module"
в файлpackage.json
- добавить указанные ниже опции в файл
tsconfig.json
{
"module": "NodeNext",
"moduleResolution": "NodeNext"
}
Для объявления мета-данных с помощью декораторов, потребуется добавить
указанные ниже опции в файл tsconfig.json
вашего проекта.
{
"emitDecoratorMetadata": true,
"experimentalDecorators": true
}
Установка и получение мета-данных с использованием ключа MetadataKey<T>
import {Reflector} from '@e22m4u/ts-metadata';
import {MetadataKey} from '@e22m4u/ts-metadata';
type MyData = {foo: string};
class Target {/* ... */}
// создание ключа MetadataKey<T>
// для мета-данных типа MyData
const key = new MetadataKey<MyData>();
// назначение мета-данных классу Target
// с помощью метода `defineMetadata`
Reflector.defineMetadata(key, {foo: 'bar'}, Target);
// метод `defineMetadata` проверяет тип
// устанавливаемого значения на соответствие
// ключу MetadataKey<MyData>, где допустимым
// значением является MyData
// TypeError: Argument of type 'string' is not assignable
// to parameter of type MyData.
Reflector.defineMetadata(key, 'string', Target);
// тип возвращаемых значений методов `getMetadata`
// и `getOwnMetadata` выводится согласно ключу
const result = Reflector.getMetadata(key, Target); // MyData
С помощью функции getDecoratorTargetType
можно определить
место применения декоратора.
import {getDecoratorTargetType} from '@e22m4u/ts-metadata';
import {DecoratorTargetType as DTT} from '@e22m4u/ts-metadata';
// объявление декоратора
function myDecorator(
target: object,
propertyKey?: string,
descriptorOrIndex?: PropertyDescriptor | number,
) {
// передача всех аргументов
// декоратора в функцию
const type = getDecoratorTargetType(
target,
propertyKey,
descriptorOrIndex,
);
// сравнение возвращаемго значения
// для определения места применения
if (type === DTT.CONSTRUCTOR)
console.log('@myDecorator is applied to a class');
if (type === DTT.STATIC_METHOD)
console.log('@myDecorator is applied to a static method');
if (type === DTT.INSTANCE_METHOD)
console.log('@myDecorator is applied to an instance method');
if (type === DTT.STATIC_PROPERTY)
console.log('@myDecorator is applied to a static property');
if (type === DTT.INSTANCE_PROPERTY)
console.log('@myDecorator is applied to an instance property');
if (type === DTT.CONSTRUCTOR_PARAMETER)
console.log('@myDecorator is applied to a constructor parameter');
if (type === DTT.STATIC_METHOD_PARAMETER)
console.log('@myDecorator is applied to a static method parameter');
if (type === DTT.INSTANCE_METHOD_PARAMETER)
console.log('@myDecorator is applied to an instance method parameter');
};
npm run test
MIT