美文网首页
TypeScript API Reflect.getMetada

TypeScript API Reflect.getMetada

作者: _扫地僧_ | 来源:发表于2021-08-15 09:03 被阅读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 帖子:

https://stackoverflow.com/questions/65246467/reflection-metadata-designparamtypes-returning-undefined-on-deno

需要修改 tsconfig.json 的内容:

添加这两行:

  "experimentalDecorators": true,
    "emitDecoratorMetadata": true,

之后问题解决:

更多Jerry的原创文章,尽在:"汪子熙":


相关文章

网友评论

      本文标题:TypeScript API Reflect.getMetada

      本文链接:https://www.haomeiwen.com/subject/zzjjultx.html