繁体   English   中英

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

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

我正在尝试使用装饰器向 class 添加新属性。 这是我的代码

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'

有没有办法让 angular 了解MyClass也有newProperty 我可以使用.d.ts文件吗?

这篇文章解决了你的问题:

如何使用 class 装饰器向 class 添加新属性?

暂无
暂无

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

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