Я записываю два файла 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
, но когда я компилирую его в js, используя tsc -p .
, результат 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)
Логика в __decorate пропустит третий аргумент ( дескриптор свойства ), когда arguments.length <= 3. Так что мой декоратор не получает дескриптор свойства <em> при выполнении кода.Но что означает третий аргумент __descriptor?Почему должен быть desc ??
Почему это случилось?Это связано с tsconfig.json?