mobx-state-tree - 可以使用types.model来模拟泛型类型吗?

时间:2017-10-13 16:05:19

标签: mobx mobx-state-tree

我第一次使用mobx-state-tree而我正在尝试使用types.model来建模泛型类型。我正在尝试使用现有的mobx代码:

/**
 * Models an Async request / response - all the properties exposed are
 * decorated with `observable.ref`; i.e. they are immutable
 */
class Async<TRequest, TResponse> implements IAsyncProps<TResponse> {
    /**
     * Whether a request is in process
     */
    @observable.ref isRequesting: boolean = false;

    /**
     * (optional) The response received last time a request was run
     */
    @observable.ref response?: TResponse;

    /**
     * (optional) The error received last time a request was run
     */
    @observable.ref error?: string;

    constructor(private process: (request: TRequest) => Promise<TResponse>) {

    }

    @action
    async run(request?: TRequest) {
        try {
            this.isRequesting = true;
            this.response = undefined;
            this.error = undefined;

            const response = await this.process(request);
            this.runSuccess(response);
        } catch (error) {
            this.runError(error);
        }
    }

    @action private runSuccess(response: TResponse) {
        this.response = response;
        this.isRequesting = false;
    }

    @action private runError(error: any) {
        this.error = error.message ? error.message : error;
        this.isRequesting = false;
    }

    @action
    reset() {
        this.isRequesting = false;
        this.response = undefined;
        this.error = undefined;
        return this;
    }
}

我希望将其移至types.model。我到目前为止:

const Async2 = types.model('Async2', {
    isRequesting: types.boolean,
    response: types.optional(/*types.? what goes here ???*/, undefined),
    error: types.optional(types.string, undefined)
});

但我仍然坚持如何通常输入响应。我可以处理其余的行动 - 有人知道这是否可行?

1 个答案:

答案 0 :(得分:1)

如果考虑泛型,它们是动态生成的类。所以你可以编写一个函数,给定两个泛型类型返回你的模型定义:)

这样的东西

Function Async(ReqType,ResType){ 。返回t.model({ 。要求:ReqType, 。 Res:ResType 。 }) }

我还建议您记住该功能,所以如果再次调用它,它将被返回相同的模型类型而不创建新的! :)