打字稿:TS7006:参数“ xxx”隐式具有“ any”类型


145

在测试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;

4
你能告诉我们你的tsconfig吗?从外观上看,您已noImplicitAny启用它,这就是导致错误的原因。
— 塞巴斯蒂安·塞巴尔

Answers:


211

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

更改此行:

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

为了这:

let user = Users.find((user: any) => user.id === query); 
// use "any" or someother 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');
//...

26
在您的tsconfig.json中,将此“ noImplicitAny”:false添加到“ compilerOptions”:{},它将起作用
— Naval Kishor Jha,

7
@ naval-kishor-jha,但是noImplicitAny是一个不错的选择,我们必须找到一个noImplicitAny为true的解决方案,这是Typescript问题吗?
— AhammadaliPK

1
有时,我遇到此问题,然后我迅速在StackOverflow上搜索,每次对这个问题生气时,我都会投赞成票:)我希望如此,我永远不会看到此页面
— Metin Atalay

55

在您的tsconfig.json文件中设置的参数"noImplicitAny": false下compilerOptions摆脱这种错误的。


32
小心。此解决方法使错误消失,仅修复症状。它不能解决根本原因。
— jbmusso

3
@jbmusso是正确的。尝试使用严格模式而不是将其关闭。这样,您就不会在运行时发现错误
— Ionel Lupu

5

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


4
将严格模式设置为false是非常糟糕的。您不会再在编译时遇到错误,但是会在运行时获取它们,您不需要这些错误。我强烈建议将严格模式设置为true
— Ionel Lupu

5

如果你得到一个错误的参数“元素”隐含有一个“任何” type.Vetur(7006) 在 vueJs

与错误:

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

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

更正的代码:

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

正是我需要的,谢谢。ForEach的“元素”需要在括号中括起来,然后才能为其分配类型。即.forEach((element:object)...
— CodeThief


0

最小的错误重现

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:防撞板(中间)

防护罩是简单类型和强类型之间的良好中间地带:
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)
}
您甚至可以切换到断言函数(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-ts或ts-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处理代码中。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.