简体   繁体   English

对 Typescript function 中的 return 语句不安全地使用“any”类型的表达式

[英]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)我一直收到此行的 lint 问题。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.我怀疑这是因为response是“通用对象”,而 typescript 无法“识别”它具有.data属性。

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:然后用它向 TS “解释” 我们期望响应包含该属性:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Typescript:ESLint:任何类型值的不安全返回 @typescript-eslint/no-unsafe-return - Typescript : ESLint : Unsafe return of an any typed value @typescript-eslint/no-unsafe-return 在TypeScript中,是否有任何方法可以将函数返回值键入函数本身? - In TypeScript, is there any method to type function return values to the function itself? Typescript:如何正确使用 Generics 来正确推断 Function 的返回类型? - Typescript: How To Use Generics Properly To Infer Return Type of Function Correctly? 打字稿中的覆盖函数返回类型 - Override function return type in typescript UIComponent.getRouterFor 显示 TypeScript 错误:“任何”类型值的不安全返回 - UIComponent.getRouterFor shows TypeScript error: Unsafe return of an 'any' typed value @typescript-eslint/no-unsafe-assignment:任何值的不安全赋值 - @typescript-eslint/no-unsafe-assignment: Unsafe assignment of an any value angular 中的 TypeScript 错误:声明类型既不是“void”也不是“any”的 function 必须返回一个值 - TypeScript error in angular: A function whose declared type is neither 'void' nor 'any' must return a value 声明类型既不是“ void”也不是“ any”的函数必须返回一个值。 TypeScript / React - A function whose declared type is neither 'void' nor 'any' must return a value. TypeScript/React 在 typescript 中使用接口而不是“任何”类型 - Use of interface instead of 'any' type in typescript Typescript - 使用数组参数中的元素作为返回类型 - Typescript - Use element in array argument as return type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM