我写了两个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 <= 3时,__ decorate中的逻辑将省略第三个参数(属性描述符)。因此,导致我的装饰器在代码编写时未获得属性描述符运行。但是__descriptor的第三个参数是什么意思?为什么需要描述?
为什么会这样?这与tsconfig.json有关吗?
答案 0 :(得分:0)
我不完全确定为什么会发生实际错误,但要回答标题问题: 您的代码起作用的最可能原因是ts-node忽略了tsconfig.json并使用了一个不同的构建目标,例如。不是es5。