I've been delving into TypeScript decorators focusing on properties, and I crafted the following snippet inspired by various examples:
decorator.ts
export function logProperty(target: any, key: string) {
let val = this[key];
const getter = () => {
console.log(`Get: ${key} => ${val}`);
return val;
};
const setter = (newVal) => {
console.log(`Set: ${key} => ${newVal}`);
val = newVal;
};
if (delete this[key]) {
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
main.ts
import { logProperty } from './decorators';
class Person {
@logProperty
firstName: string;
@logProperty
lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
}
const foo = new Person('Foo', 'Bar');
My challenge lies in encountering the following error when attempting to execute this setup:
TypeError: Cannot read property 'firstName' of undefined
The underlying issue appears to be related to the undefined value for this
. Can anyone help me identify what's missing?
For clarifications, my tsconfig.json
includes:
"target": "es5"
"experimentalDecorators": true
"strict": false
UPDATE 8/27
The problem seemingly arises only when the decorator is placed in a separate .ts
file. The error doesn't manifest when everything is consolidated within a single file. Could it be an oversight in how this
is being interpreted?