简体   繁体   中英

Unsafe use of expression of type 'any' for return statements in Typescript function

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()
    })
}

I keep getting a lint issue for this line .then((response): object => response.data)

which states Unsafe use of expression of type 'any'

I suspect that it's because response is a "generic object" and typescript can't "identify" that it has a .data attribute.

In order to fix that we can declare an interface of a type:

type hasData = { data: any };

and then use it to "explain" to TS that we expect the response to contain that attribute:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM