Tim*_*win 4 typescript reflect-metadata
我有一个打字稿项目,想检查一些对象。所以我安装reflect-metadata、启用experimentalDeorators并emitDecoratorMetadata在tsconfig.json. 然后我有这个代码:
import 'reflect-metadata';
class Bla {
thing: string;
}
console.log(Bla, Reflect.getMetadata('design:type', Bla, 'thing'));
Run Code Online (Sandbox Code Playgroud)
它输出undefined. 我希望得到String或其他东西。另外,编译后的 Javascript 如下所示:
var Bla = /** @class */ (function () {
function Bla() {
}
return Bla;
}());
console.log(Bla, Reflect.getMetadata('design:type', Bla, 'thing'));
Run Code Online (Sandbox Code Playgroud)
没有用于设置元数据的代码。有趣的是,在我添加自定义装饰器时,我看到了用于设置元数据的代码:
function deco(target, key) { }
var Bla = /** @class */ (function () {
function Bla() {
}
__decorate([
deco,
__metadata("design:type", String)
], Bla.prototype, "thing", void 0);
return Bla;
}());
console.log(Bla, Reflect.getMetadata('design:type', Bla, 'thing'));
Run Code Online (Sandbox Code Playgroud)
但我还是明白了undefined。我也尝试过Bla.prototype,没有改变。知道这里出了什么问题吗?
这是设计使然,装饰器元数据仅在装饰成员上发出。这是PR及其引用的问题,标题和第一行说明了一切:
为装饰器发出序列化的设计时类型元数据
添加对实验性编译器选项的支持,以便为源中的修饰声明发出设计类型元数据。
(强调已添加)
添加装饰器时的问题是您需要检查prototype:
import 'reflect-metadata';
function deco(target, key) { }
class Bla {
@deco thing: string;
}
console.log(Reflect.getMetadata('design:type', Bla.prototype, 'thing')); // outputs String
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3086 次 |
| 最近记录: |