sách gpt4 ăn đã đi

typescript 添加装饰器类型的方法不存在

In lại 作者:搜寻专家 更新时间:2023-10-30 21:08:21 27 4
mua khóa gpt4 giày nike

我想创建一个装饰器,为类添加一个方法。

export function Deco() {
return function(constructor: T) {
constructor.prototype.someMethod = function() {

};
};
}


@Deco()
lớp Kiểm tra {

}

问题是当我尝试调用添加的方法时,出现 typescript 错误:

Property someMethod does not exist on type Test.

const test = new Test();

test.someMethod();

Làm thế nào tôi có thể giải quyết vấn đề này?

câu trả lời hay nhất

装饰器不能影响类型的结构。有一个简单的解决方法。用类调用装饰器,并在函数内部用你想要的方法创建一个派生类。该函数的结果将是新的“装饰”类,它将具有所有方法:

export function Deco() {
return function (constructor: T) {
return class extends constructor {
someMethod() {

}
}
};
}


let Test = Deco()(class {
// Other stuff
});

const test = new Test();
test.someMethod();

关于 typescript 添加装饰器类型的方法不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48599889/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress