TypeScript API Reflect.getMetadata 返回 undefined 的解决办法
生活随笔
收集整理的這篇文章主要介紹了
TypeScript API Reflect.getMetadata 返回 undefined 的解决办法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
我有下面這段測試代碼:
function validate(target: Object,key: string,descriptor: PropertyDescriptor ) {const originalFn = descriptor.value;// 獲取參數(shù)的編譯期類型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 {@validatesayRepeat(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執(zhí)行時(shí),發(fā)現(xiàn)第 17 行的代碼,Reflect.getMetadata 返回 undefined:
經(jīng)過研究,發(fā)現(xiàn)了這個(gè) StackOverflow 帖子:
https://stackoverflow.com/questions/65246467/reflection-metadata-designparamtypes-returning-undefined-on-deno
需要修改 tsconfig.json 的內(nèi)容:
添加這兩行:
"experimentalDecorators": true,"emitDecoratorMetadata": true,之后問題解決:
更多Jerry的原創(chuàng)文章,盡在:“汪子熙”:
總結(jié)
以上是生活随笔為你收集整理的TypeScript API Reflect.getMetadata 返回 undefined 的解决办法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用 TypeScript 自定义装饰器
- 下一篇: TypeScript reflect-m