我是第一次使用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)
});但是我被困在如何通用地键入响应上。我可以处理剩下的操作--有人知道这是否可能吗?
发布于 2017-10-15 14:24:34
如果你考虑泛型,它们是动态生成的类。因此,您只需编写一个函数,在给定两个泛型类型的情况下,使用它们返回模型定义:)
就像这样
函数异步(ReqType,ResType){ .返回t.model({ .请求: ReqType,.Res: ResType。}) }
我还建议您记住该函数,因此如果您再次调用它,它将返回相同的模型类型,而不会创建新的模型类型!:)
https://stackoverflow.com/questions/46733922
复制相似问题