TypeScript API Reflect.getMetada
2021-08-15 本文已影响0人
_扫地僧_
我有下面这段测试代码:
function validate(
target: Object,
key: string,
descriptor: PropertyDescriptor
) {
const originalFn = descriptor.value;
// 获取参数的编译期类型
const designParamTypes = Reflect
.getMetadata('design:paramtypes', target, key);
descriptor.value = function (...args: any[]) {
args.forEach((arg, index) => {
const paramType = designParamTypes[index];
const result = arg.constructor === paramType
|| arg instanceof paramType;
if (!result) {
throw new Error(
`Failed for validating parameter: ${arg} of the index: ${index}`
);
}
});
return originalFn.call(this, ...args);
}
}
class C {
@validate
sayRepeat(word: string, x: number) {
return Array(x).fill(word).join('');
}
}
const c = new C();
console.log('Ethan');
c.sayRepeat('hello', 2); // pass
c.sayRepeat('', 'lol' as any); // throw an error
执行时,发现第 17 行的代码,Reflect.getMetadata 返回 undefined:
经过研究,发现了这个 StackOverflow 帖子:
需要修改 tsconfig.json 的内容:
添加这两行:
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
之后问题解决:
更多Jerry的原创文章,尽在:"汪子熙":