gpt4 book ai didi

javascript - TypeScript 装饰器无法识别新属性

转载 作者:行者123 更新时间:2023-12-01 02:33:19 36 4
gpt4 key购买 nike

假设我有一个类装饰器,它向类添加一些方法。

function decorator(target) {
target.prototype.method = function() {};
}


@decorator
class Test {
constructor() {
this.method() <------- Property method does not exists on type Test
}
}

如果我有能力添加装饰器,但 typescript 无法识别它们,那么它就毫无值(value)。

有办法解决这个问题吗?

最佳答案

装饰器的使用有各种各样的原因,从修改类到面向方面的编程,再到简单的日志记录。装饰器内部几乎任何事情都可能发生。此时,装饰器的内容不用于修改类的类型信息(在某些情况下,可能永远不可能这样做,尽管在您的情况下这是可能的,因为它是如此简单) )。

如果你想向类添加方法,你可以考虑 TypeScript mixins作为替代方案,或简单继承(见下文)。

占位符实现

解决您的问题的一个简单方法是提供一个空方法来生成您想要的类型信息:

@decorator
class Test {
constructor() {
this.method();
}

method(): void { }
}

替换构造函数

另一种解决方案是替换装饰器中的构造函数 - 因此您可以在装饰器内添加方法以及对该方法的构造函数调用 - 从而确保实现在那里。

function decorator(target: any) {
const original = target;

const constr: any = (...args) => {
const c: any = () => {
return original.apply(null, args);
}

c.prototype = original.prototype;
c.prototype.method = function () { alert('method');};

const inst = new c();
inst.method();
return inst;
}

constr.prototype = original.prototype;

return constr;

}

@decorator
class Test {
constructor() {
}
}

const test = new Test();

继承

这是一个无聊但通常是正确的解决方案(如果您不想继承,您可以委托(delegate)代替):

class HasMethod {
method() {
alert('Method');
}
}

class Test extends HasMethod {
constructor() {
super();
this.method();
}
}

const test = new Test();

关于javascript - TypeScript 装饰器无法识别新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48151906/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com