我想添加方法setStatePromisified
来反应组件的原型,我试图使用装饰器实现这一点:
interface IPromisifiedComponent {
setStatePromise: (state) => Promise<void>
}
interface IPromisifiedComponentConstructor {
new (...args): IPromisifiedComponent;
readonly prototype: IPromisifiedComponent;
}
function promisifiedDecorator() {
return function (Component: IPromisifiedComponentConstructor) {
Component.prototype.setStatePromise = (state) => {
return new Promise<void>((resolve) => {
this.setState(state, () => {
resolve();
});
});
};
}
}
@promisifiedDecorator()
class TestComponent extends React.Component<any, any> implements IPromisifiedComponent {
}
Typescript要求实现setStatePromise
方法:类型setStatePromise
中缺少属性Test
。我该怎么做才能解决这个错误?
答案 0 :(得分:1)
编译器抱怨,因为TestComponent
被定义为实现IPromisifiedComponent
但它缺少此接口定义的setStatePromise
方法。
你在运行时使用装饰器添加这个方法的事实对于编译器来说还不够好,所以你需要让它知道它没关系,你知道你在做什么:
@promisifiedDecorator()
class TestComponent extends React.Component<any, any> implements IPromisifiedComponent {
setStatePromise: (state: any) => Promise<void>;
}
此外,如果您的装饰者不需要任何参数,那么您只需执行以下操作:
function promisifiedDecorator(Component: IPromisifiedComponentConstructor) {
Component.prototype.setStatePromise = (state) => {
return new Promise<void>((resolve) => {
this.setState(state, () => {
resolve();
});
});
};
}
@promisifiedDecorator
class TestComponent extends React.Component<any, any> implements IPromisifiedComponent {
setStatePromise: (state: any) => Promise<void>;
}