首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >mobx-state-tree - types.model可以用于泛型类型建模吗?

mobx-state-tree - types.model可以用于泛型类型建模吗?
EN

Stack Overflow用户
提问于 2017-10-14 00:05:19
回答 1查看 800关注 0票数 2

我是第一次使用mobx-state-tree,并尝试使用types.model对泛型类型进行建模。我正在尝试使用现有的mobx代码:

代码语言:javascript
复制
/**
 * 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上。我已经做到了这一点:

代码语言:javascript
复制
const Async2 = types.model('Async2', {
    isRequesting: types.boolean,
    response: types.optional(/*types.? what goes here ???*/, undefined),
    error: types.optional(types.string, undefined)
});

但是我被困在如何通用地键入响应上。我可以处理剩下的操作--有人知道这是否可能吗?

EN

回答 1

Stack Overflow用户

发布于 2017-10-15 14:24:34

如果你考虑泛型,它们是动态生成的类。因此,您只需编写一个函数,在给定两个泛型类型的情况下,使用它们返回模型定义:)

就像这样

函数异步(ReqType,ResType){ .返回t.model({ .请求: ReqType,.Res: ResType。}) }

我还建议您记住该函数,因此如果您再次调用它,它将返回相同的模型类型,而不会创建新的模型类型!:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46733922

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档