Typescript 不发出装饰器元数据
Typescript emits no decorator metadata
我有一个打字稿项目,想检查一些对象。所以我安装了 reflect-metadata
,在 tsconfig.json
中启用了 experimentalDeorators
和 emitDecoratorMetadata
。然后我有这个代码:
import 'reflect-metadata';
class Bla {
thing: string;
}
console.log(Bla, Reflect.getMetadata('design:type', Bla, 'thing'));
输出undefined
。我希望得到 String
或其他东西。此外,编译后的 Javascript 如下所示:
var Bla = /** @class */ (function () {
function Bla() {
}
return Bla;
}());
console.log(Bla, Reflect.getMetadata('design:type', Bla, 'thing'));
没有设置元数据的代码。有趣的是,在我添加自定义装饰器的那一刻,我看到为设置元数据发出的代码:
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'));
但我还是得到 undefined
。我也试了Bla.prototype
,没有变化。知道这里出了什么问题吗?
这是设计使然,装饰器元数据仅在装饰成员上发出。这是它引用的 PR and the issue,标题和第一行说明了一切:
Emit serialized design-time type metadata for decorators
Add support behind an experimental compiler option to emit design-type metadata for decorated declarations in source.
(强调已添加)
添加装饰器时的问题是您需要检查 prototype
:
import 'reflect-metadata';
function deco(target, key) { }
class Bla {
@deco thing: string;
}
console.log(Reflect.getMetadata('design:type', Bla.prototype, 'thing')); // outputs String
我有一个打字稿项目,想检查一些对象。所以我安装了 reflect-metadata
,在 tsconfig.json
中启用了 experimentalDeorators
和 emitDecoratorMetadata
。然后我有这个代码:
import 'reflect-metadata';
class Bla {
thing: string;
}
console.log(Bla, Reflect.getMetadata('design:type', Bla, 'thing'));
输出undefined
。我希望得到 String
或其他东西。此外,编译后的 Javascript 如下所示:
var Bla = /** @class */ (function () {
function Bla() {
}
return Bla;
}());
console.log(Bla, Reflect.getMetadata('design:type', Bla, 'thing'));
没有设置元数据的代码。有趣的是,在我添加自定义装饰器的那一刻,我看到为设置元数据发出的代码:
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'));
但我还是得到 undefined
。我也试了Bla.prototype
,没有变化。知道这里出了什么问题吗?
这是设计使然,装饰器元数据仅在装饰成员上发出。这是它引用的 PR and the issue,标题和第一行说明了一切:
Emit serialized design-time type metadata for decorators
Add support behind an experimental compiler option to emit design-type metadata for decorated declarations in source.
(强调已添加)
添加装饰器时的问题是您需要检查 prototype
:
import 'reflect-metadata';
function deco(target, key) { }
class Bla {
@deco thing: string;
}
console.log(Reflect.getMetadata('design:type', Bla.prototype, 'thing')); // outputs String