Skip to content
Advertisement

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’

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement