javascript - 在 Typescript 函数中对 return 语句不安全地使用“any”类型的表达式
问题描述
async fetchDetail(token: string): Promise < object > {
const headersRequest = {
Authorization: `Basic ${token}`,
'Content-Type': 'application/json',
}
return await this.httpService.get( < URL > , {
headers: headersRequest
})
.toPromise()
.then((response): object => response.data)
.catch(() => {
throw new NotFoundException()
})
}
我不断收到这条线的 lint 问题.then((response): object => response.data)
说明 “任何”类型表达式的不安全使用
解决方案
我怀疑这是因为它response
是一个“通用对象”并且打字稿无法“识别”它具有.data
属性。
为了解决这个问题,我们可以声明一个类型的接口:
type hasData = { data: any };
然后用它向 TS “解释” 我们期望响应包含该属性:
.then((response: hasData): object => response.data)
推荐阅读
- android - 反应本机崩溃:线程:SIGSEGV libjsc.so
- firebase - 需要继续检查颤振应用程序的身份验证类型
- delphi - Delphi 10.4 和 TRESTRequest 导致未知错误 Webbroker ISAPI DLL
- kubernetes - Kubernetes POD 线程耗尽,变得无响应且从未恢复
- postgresql - 将 PostgreSQL 服务与 DreamFactory 一起使用时出现“500 无法检索记录”错误
- javascript - 这个错误是怎么回事?我更改了表的类名,但我无法更改它并出现此错误?
- python - 如何使用列表理解改进以下代码片段
- python - 我不明白这些代码之间的区别
- reactjs - 令牌在前端是正确的,但在后端它是未定义的
- python - 将值分配给列表更改成员列表