正如在 Superagent 类型中看到的那样,request.agent() 返回 SuperAgent<SuperAgentRequest> that doesn't have timeout method,这就是错误消息的内容。
虽然timeout 方法存在于Request 类型中,但它是响应的承诺。这就是引发此错误的原因。没有请求,也没有回应。 Superagent documentation 提供了timeout 的示例:
request
.get('/big-file?network=slow')
.timeout({
response: 5000, // Wait 5 seconds for the server to start sending,
deadline: 60000, // but allow 1 minute for the file to finish loading.
})
文档指出代理实例具有methods that set defaults,因此缺少类型。没有deadline 方法,用timeout 也没有意义,因为这是deadline timeout。
superagent 类型应该在本地增加,或者被改进并 PRed 到 DefinitiveTyped 存储库,或者就地固定:
{
provide: request,
useFactory: () =>
<SuperAgent<SuperAgentRequest>>request.agent()
['timeout'](30)
}
我希望增强类型类似于(使用正则表达式处理原始Request 接口):
custom.d.ts
import * as request from 'superagent';
type CallbackHandler = (err: any, res: request.Response) => void;
type Serializer = (obj: any) => string;
type BrowserParser = (str: string) => any;
type NodeParser = (res: request.Response, callback: (err: Error | null, body: any) => void) => void;
type Parser = BrowserParser | NodeParser;
declare module "superagent" {
interface ConfigurableSuperAgent<Req extends request.SuperAgentRequest> extends request.SuperAgent<Req> {
accept(type: string): this;
auth(user: string, name: string): this;
buffer(val?: boolean): this;
ca(cert: Buffer): this;
cert(cert: Buffer | string): this;
key(cert: Buffer | string): this;
ok(callback: (res: Response) => boolean): this;
on(name: 'error', handler: (err: any) => void): this;
on(name: 'progress', handler: (event: ProgressEvent) => void): this;
on(name: string, handler: (event: any) => void): this;
parse(parser: Parser): this;
pfx(cert: Buffer | string): this;
query(val: object | string): this;
redirects(n: number): this;
retry(count?: number, callback?: CallbackHandler): this;
serialize(serializer: Serializer): this;
set(field: object): this;
set(field: string, val: string): this;
timeout(ms: number | { deadline?: number, response?: number }): this;
type(val: string): this;
use(fn: Plugin): this;
}
interface SuperAgentStatic extends request.SuperAgent<request.SuperAgentRequest> {
agent(): ConfigurableSuperAgent<request.SuperAgentRequest>;
}
}