【发布时间】:2022-12-31 08:36:11
【问题描述】:
我有一个简单的类
class Component {
@id() instanceId: string;
@id() secondaryId: string;
log() {
console.log(this.instanceId, this.secondaryId);
}
}
和一个装饰师
const id = (): PropertyDecorator => {
return (target, name) => {
const descriptor = {
get(this: any) {
const propertyName = `__${String(name)}`;
if (!this[propertyName]) {
this[propertyName] = 'MY ID';
}
return this[propertyName];
},
enumerable: true,
configurable: true
};
Object.defineProperty(target, name, descriptor);
};
};
我的tsconfig.json 看起来像这样:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"alwaysStrict": true,
"esModuleInterop": true,
"declaration": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strictPropertyInitialization": false,
"target": "ESNext",
"module": "CommonJS",
"moduleResolution": "node",
"types": [
"node"
]
}
}
当我执行以下操作时:
const cmp = new Component();
cmp.log();
我希望 "MY ID", "MY ID" 将打印在控制台中,但我得到的是 undefined, undefined。
此示例在 TS playground (link) 中按预期工作,但在本地甚至在 CodeSandbox (link) 上都不起作用。
怎么了?
【问题讨论】:
-
您在本地使用的是什么版本的 Typescript?什么是转译器输出?
标签: javascript typescript typescript-decorator