使用装饰器扩展原型

时间:2016-10-24 11:47:58

标签: javascript reactjs typescript decorator

我想添加方法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。我该怎么做才能解决这个错误?

1 个答案:

答案 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>;
}