首页 > 解决方案 > 在 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)

说明 “任何”类型表达式的不安全使用

标签: javascriptnode.jstypescriptbackendnestjs

解决方案


我怀疑这是因为它response是一个“通用对象”并且打字稿无法“识别”它具有.data属性。

为了解决这个问题,我们可以声明一个类型的接口:

type hasData = { data: any };

然后用它向 TS “解释” 我们期望响应包含该属性:

.then((response: hasData): object => response.data)

推荐阅读