【发布时间】:2019-02-24 15:53:18
【问题描述】:
我写了两个ts文件来测试装饰器。
index.ts
import { lockMethod } from './dec';
class Person {
walk() {
console.info(`I am walking`);
}
@lockMethod
run() {
console.info(`I am running`);
}
}
const person = new Person();
person.walk();
dec.ts
export function lockMethod(target: any, name: any, descriptor: any): any {
descriptor.configurable = false;
}
tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"noImplicitAny": true,
"noUnusedLocals": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"experimentalDecorators": true,
"lib": ["es7", "dom"],
"baseUrl": "./",
"paths": {},
"outDir": "./dist",
"target": "es5"
},
"exclude": [
"node_modules"
]
}
当我运行 ts-node index.ts 时,它记录了正确的东西 I am walking,但是当我使用 tsc -p . 将它编译成 js 时,结果 js 包含一个错误。
下面是格式化的js文件。
index.js
"use strict";
var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ?
target :
desc === null ?
desc = Object.getOwnPropertyDescriptor(target, key) :
desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else {
for (var i = decorators.length - 1; i >= 0; i--) {
if (d = decorators[i]) {
r = (
c < 3 ?
d(r) :
c > 3 ?
d(target, key, r) :
d(target, key)
) || r;
}
}
}
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
var dec_1 = require("./dec");
var Person = /** @class */ (function() {
function Person() {}
Person.prototype.walk = function() {
console.info("I am walking");
};
Person.prototype.run = function() {
console.info("I am running");
};
__decorate([
dec_1.lockMethod
], Person.prototype, "run");
return Person;
}());
var person = new Person();
person.walk();
当我运行node index.js 时,错误是
TypeError: Cannot set property 'configurable' of undefined
at lockMethod (/Users/un/Documents/code/test/temp-ts/dec.js:4:29)
at __decorate (/Users/un/Documents/code/test/temp-ts/index.js:20:15)
at /Users/un/Documents/code/test/temp-ts/index.js:37:3
at Object.<anonymous> (/Users/un/Documents/code/test/temp-ts/index.js:41:2)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
当arguments.length 属性描述符)。所以它会导致我的装饰器在编码时没有得到属性描述符跑步。但是 __descriptor 的第三个参数是什么意思?为什么需要一个描述?
为什么会这样?这和tsconfig.json有关吗?
【问题讨论】:
-
错误是什么?
标签: javascript typescript typescript-decorator