【问题标题】:Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type打字稿:TS7006:参数“xxx”隐式具有“任何”类型
【发布时间】:2017-08-21 05:05:35
【问题描述】:

在测试我的 UserRouter 时,我使用的是 json 文件

data.json

[
  {
    "id": 1,
    "name": "Luke Cage",
    "aliases": ["Carl Lucas", "Power Man", "Mr. Bulletproof", "Hero for Hire"],
    "occupation": "bartender",
    "gender": "male",
    "height": {
      "ft": 6,
      "in": 3
    },
    "hair": "bald",
    "eyes": "brown",
    "powers": [
      "strength",
      "durability",
      "healing"
    ]
  },
  {
  ...
  }
]

构建我的应用程序,我收到以下 TS 错误

ERROR in ...../UserRouter.ts
(30,27): error TS7006: Parameter 'user' implicitly has an 'any' type.

UserRouter.ts

import {Router, Request, Response, NextFunction} from 'express';
const Users = require('../data');

export class UserRouter {
  router: Router;

  constructor() {
  ...
  }

  /**
   * GET one User by id
   */
  public getOne(req: Request, res: Response, _next: NextFunction) {
    let query = parseInt(req.params.id);
 /*[30]->*/let user = Users.find(user => user.id === query);
    if (user) {
      res.status(200)
        .send({
          message: 'Success',
          status: res.status,
          user
        });
    }
    else {
      res.status(404)
        .send({
          message: 'No User found with the given id.',
          status: res.status
        });
    }
  }


}

const userRouter = new UserRouter().router;
export default userRouter;

【问题讨论】:

  • 你能告诉我们你的tsconfig吗?从外观上看,您启用了noImplicitAny,这就是导致错误的原因。
  • 所有这些建议您禁用 strictnoImplicitAny 的 cmets 和答案都很糟糕。您不妨使用 JavaScript。

标签: typescript


【解决方案1】:

tsconfig.json 文件的 compilerOptions 部分中进行这些更改,这对我有用

"noImplicitAny": false

无需设置

"strict":false

请等待 1 到 2 分钟,有些电脑编译速度很慢

【讨论】:

    【解决方案2】:

    我在 Angular 中发现函数参数存在这个问题。

    在我的代码给出错误之前

    参数 'event' 隐含一个 'any' 类型

    这是代码

    changeInpValue(event)
    {
        this.inp = event.target.value;
    }
    

    这里是变化,参数写入: any后,错误就解决了

    changeInpValue(event : any)
    {
        this.inp = event.target.value;
    }
    

    对我来说工作得很好。

    【讨论】:

      【解决方案3】:

      参数 'post' 在 Angularcli 中隐式具有 'any' 类型 也许在创建项目时,您在应用程序中启用了 Angular 的严格模式? Max 建议禁用严格模式 如果您启用了严格模式,请通过将 tsconfig.json 中的 strict 属性设置为 false

      来为本课程禁用它

      【讨论】:

        【解决方案4】:

        在您的 tsconfig.json 文件中添加以下规则:- "strict": false /* does not allow all strict type-checking options. */,

        【讨论】:

          【解决方案5】:

          转到 tsconfig.json 并注释 //strict:true 这对我有用

          【讨论】:

            【解决方案6】:

            您正在使用 --noImplicitAny 并且 TypeScript 不知道 Users 对象的类型。在这种情况下,您需要显式定义user 类型。

            改变这一行:

            let user = Users.find(user => user.id === query);
            

            到这里:

            let user = Users.find((user: any) => user.id === query); 
            // use "any" or some other interface to type this argument
            

            或者定义你的Users对象的类型:

            //...
            interface User {
                id: number;
                name: string;
                aliases: string[];
                occupation: string;
                gender: string;
                height: {ft: number; in: number;}
                hair: string;
                eyes: string;
                powers: string[]
            }
            //...
            const Users = <User[]>require('../data');
            //...
            

            【讨论】:

            • 在你的 tsconfig.json 中添加这个 "noImplicitAny": false 到 "compilerOptions":{} 它会起作用
            • @naval-kishor-jha ,但是 noImplicitAny 是一个不错的选择,我们必须找到一个 noImplicitAny 为 true 的解决方案,这是 Typescript 问题吗?
            • 有时,我遇到这个问题,然后我快速搜索 StackOverflow,我看到了我给你的投票,每次我为这个问题生自己的气 :) 我希望如此,我永远不会看到这个页面
            【解决方案7】:

            最小的错误重现

            export const users = require('../data'); // presumes @types/node are installed
            const foundUser = users.find(user => user.id === 42); 
            // error: Parameter 'user' implicitly has an 'any' type.ts(7006)
            

            推荐解决方案:--resolveJsonModule

            对于您的情况,最简单的方法是使用 --resolveJsonModule 编译器选项:
            import users from "./data.json" // `import` instead of `require`
            const foundUser = users.find(user => user.id === 42); // user is strongly typed, no `any`!
            

            对于静态 JSON 导入之外的其他情况,还有一些替代方案。

            选项 1:显式用户类型(简单,无检查)

            type User = { id: number; name: string /* and others */ }
            const foundUser = users.find((user: User) => user.id === 42)
            

            选项 2:类型保护(中间)

            Type guards 是简单类型和强类型之间的一个很好的中间地带:
            function isUserArray(maybeUserArr: any): maybeUserArr is Array<User> {
              return Array.isArray(maybeUserArr) && maybeUserArr.every(isUser)
            }
            
            function isUser(user: any): user is User {
              return "id" in user && "name" in user
            }
            
            if (isUserArray(users)) {
              const foundUser = users.find((user) => user.id === 42)
            }
            
            您甚至可以切换到 assertion functions (TS 3.7+) 以摆脱 if 并抛出错误。
            function assertIsUserArray(maybeUserArr: any): asserts maybeUserArr is Array<User> {
              if(!isUserArray(maybeUserArr)) throw Error("wrong json type")
            }
            
            assertIsUserArray(users)
            const foundUser = users.find((user) => user.id === 42) // works
            

            选项 3:运行时类型系统库(复杂)

            对于更复杂的情况,可以集成像 io-tsts-runtime 这样的运行时类型检查库。


            推荐解决方案

            noImplicitAny: false 破坏了对类型系统的许多有用检查:
            function add(s1, s2) { // s1,s2 implicitely get `any` type
              return s1 * s2 // `any` type allows string multiplication and all sorts of types :(
            }
            add("foo", 42)
            

            还更好地为user 提供明确的User 类型。这将避免将any 传播到内层类型。相反,键入和验证保留在外部 API 层的 JSON 处理代码中。

            【讨论】:

              【解决方案8】:

              如果您收到错误,因为 参数“元素”隐含地具有“任何”类型。Vetur(7006)vueJs

              出现错误:

               exportColumns.forEach(element=> {
                    if (element.command !== undefined) {
                      let d = element.command.findIndex(x => x.name === "destroy");
              

              您可以通过如下定义这些变量来修复它。

              更正的代码:

              exportColumns.forEach((element: any) => {
                    if (element.command !== undefined) {
                      let d = element.command.findIndex((x: any) => x.name === "destroy");
              

              【讨论】:

              • 这正是我所需要的,谢谢。 ForEach 的“元素”需要用括号括起来,然后才能为其分配类型。即 .forEach((element: object)...
              【解决方案9】:

              在您的tsconfig.json 文件中,设置compilerOptions 下的参数"noImplicitAny": false 以消除此错误。

              【讨论】:

              • 小心。此解决方法可以消除错误并仅修复症状;它不能解决根本原因。
              • @jbmusso 是对的。尝试使用严格模式而不是关闭它。这样你就不会在运行时发现错误
              【解决方案10】:

              我遇到了这个错误,发现是因为tsconfig.json文件中的“strict”参数设置为true。只需将其设置为“假”(显然)。在我的例子中,我从 cmd 提示符生成了 tsconfig 文件,只是错过了位于文件下方的“严格”参数。

              【讨论】:

              • 将严格模式设置为 false 非常糟糕。您不会再在编译时收到错误,但您会在运行时收到它们,这是您不想要的。我强烈建议将严格模式设置为true
              猜你喜欢
              • 2021-11-17
              • 1970-01-01
              • 2023-03-08
              • 2020-02-02
              • 2021-03-29
              • 2018-11-30
              • 2020-01-06
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多