【发布时间】:2021-06-16 22:50:57
【问题描述】:
我试图根据一些参数调用一个方法,但我无法编译它。
我遇到的错误:
test/unit/account-client/AccountGateway.spec.ts:59:10 - error TS2349: This expression is not callable.
Each member of the union type '(<T = any>(params: GetRequestParams) => Promise<HttpResponse<T>>) | (<T = any>(params: PutRequestParams) => Promise<HttpResponse<T>>) | (<T = any>(params: PutRequestParams) => Promise<...>)' has signatures, but none of those signatures are compatible with each other.
59 when(x[httpVerb](anything())).thenResolve(success);
~~~~~~~~~~~
test/unit/account-client/AccountGateway.spec.ts:59:47 - error TS2345: Argument of type '{ statusCode: number; headers: {}; body: { id: string; }; }' is not assignable to parameter of type 'void'.
59 when(x[httpVerb](anything())).thenResolve(success);
~~~~~~~
Found 2 errors.
代码首次尝试:
function whenAccountApiRequestSucceeds(httpVerb: 'get' | 'post' | 'patch') {
const success = {
statusCode: 200,
headers: {},
body: account,
};
when(httpClient[httpVerb](anything())).thenResolve(success);
}
第二次尝试,产生上述错误:
function whenAccountApiRequestSucceeds(httpVerb: 'get' | 'post' | 'patch') {
const success = {
statusCode: 200,
headers: {},
body: account,
};
const x = {
get: httpClient.get,
post: httpClient.post,
patch: httpClient.patch,
};
when(x[httpVerb](anything())).thenResolve(success);
}
第三次尝试使用Pick 和keyof,httpClient 是HttpClient 类的一个实例:
function whenAccountApiRequestSucceeds(
httpVerb: Pick<keyof HttpClient, 'get' | 'post' | 'patch'>,
) {
const success = {
statusCode: 200,
headers: {},
body: account,
};
when(httpClient[httpVerb](anything())).thenResolve(success);
}
这次我什至遇到了 lint 错误:
Type 'Pick<keyof HttpClient, "get" | "post" | "patch">' cannot be used as an index type.ts(2538)- `键入“获取”| “帖子” | "patch"' 不满足约束 'number | "toString" | charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" |"replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | ... 31 更多 ... | "trimRight"'.'.ts(2344)'
仅作记录,本作品没有错误:
function whenAccountApiRequestSucceeds(_httpVerb: 'get' | 'post' | 'patch') {
const success = {
statusCode: 200,
headers: {},
body: account,
};
when(httpClient['get'](anything())).thenResolve(success);
when(httpClient['post'](anything())).thenResolve(success);
when(httpClient['patch'](anything())).thenResolve(success);
}
when()、anything() 和 .thenResolve() 是 ts-mockito 函数
我需要做什么才能使这个动态方法调用正常工作?
【问题讨论】:
-
请考虑修改此处的代码以构成一个minimal reproducible example,当按原样放入The TypeScript Playground 之类的独立IDE 时,它会演示您的问题,或者如果失败,请考虑提供指向已配置Web 的链接演示该问题的 IDE 项目。这将允许想要回答的人开始研究解决方案,而不是首先花费时间来重现问题。祝你好运!