简体   繁体   English

如何使用 typescript 中的装饰器向 class 添加和声明新属性(角度)

[英]How to add and declare new property to class using decorator in typescript (angular)

I'm trying to add new property to class using decorator.我正在尝试使用装饰器向 class 添加新属性。 Here is my code这是我的代码

function classDecorator<T extends {new(...args: any[]): {}}>(constructor: T) {
    constructor.prototype.newProperty = 'some value';
}


@classDecorator
class MyClass {
  property1: string = 'value1';
  property2: string = 'value1';
}
const obj = new MyClass();

console.log(obj);
console.log(obj.property1);
console.log(obj.property2);
console.log(obj.newProperty); //  error TS2551: Property 'newProperty' does not exist on type 'MyClass'

Is there any way to make angular to understand that MyClass also have newProperty ?有没有办法让 angular 了解MyClass也有newProperty Can I do it with .d.ts file?我可以使用.d.ts文件吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM