CodexBloom - Programming Q&A Platform

TypeScript class decorator causing issues with instance properties initialization

👀 Views: 87 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
typescript class decorators TypeScript

I'm using TypeScript version 4.5 and trying to create a class decorator that adds a property to my class instances. However, I'm encountering an issue where the property isn't being initialized as expected when creating an instance of the class. Here's what I've implemented: ```typescript function AddProperty(target: Function) { target.prototype.newProperty = 'Hello'; } @AddProperty class MyClass { public existingProperty: string; constructor(value: string) { this.existingProperty = value; } } const instance = new MyClass('World'); console.log(instance.newProperty); // undefined console.log(instance.existingProperty); // 'World' ``` Despite applying the decorator, `newProperty` remains `undefined` in the instance. I've verified that the decorator is being applied, as I can see other properties being added. However, it seems that instance properties initialized in the constructor are not being recognized alongside the properties added by the decorator. I've also tried defining the property explicitly in the class like this: ```typescript declare global { interface MyClass { newProperty: string; } } ``` But this does not resolve the issue. Any suggestions on how to get `newProperty` to initialize correctly? Is there something I'm missing with the decorator pattern or class property declarations in TypeScript? I've looked into the TypeScript handbook and tried various approaches, but none seem to work. Could this be related to how TypeScript handles properties at runtime?