我在TypeScript项目中使用superagent
,并安装了@types/superagent
,但看到我不理解的类型错误。鉴于以下...
const myRequest = request
.get('/path/to/api')
.end((err, res) => {
// Do stuff with err and res
})
我收到err
和res
的这些错误:Parameter 'err' implicitly has an 'any' type.ts(7006)
Parameter 'res' implicitly has an 'any' type.ts(7006)
但是同时TypeScript似乎确实知道这些变量的类型,因为当我在VSCode中将其悬停在变量上时,它会显示@types/superagent
中的正确类型,如下图所示。
在图像中显示它正在从res
正确获取request.Response
的类型为@types/superagent
。
因此,我不明白为什么会收到这些隐式类型错误。有人能向TypeScript新手解释吗?谢谢:)
您未指定参数的类型。尝试以下操作:
const myRequest = request
.get('/path/to/api')
.end((err, res: request.Response) => {
// Do stuff with err and res
})
您正在使用superagent.d.ts
,并且end
方法使用以CallbackHandler
作为输入参数的res: request.Response
。
end(callback?: CallbackHandler): this;
和
type CallbackHandler = (err: any, res: request.Response) => void;
因此,typescript
推断您必须将res
设置为request.Response
[superagent.d.ts
Source Code