443

In testing my UserRouter, I am using a json file

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"
    ]
  },
  {
  ...
  }
]

Building my app, I get the following TS error

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;
3
  • 10
    Can you show us your tsconfig? By the look of it you have noImplicitAny enabled and that is what causing the error. Mar 28, 2017 at 8:53
  • 15
    All these comments and answers suggesting that you disable strict or noImplicitAny are terrible. You might as well use JavaScript.
    – Steve
    Jun 24, 2021 at 13:37
  • Thank you both. I shall use these settings temporarily!
    – R Claven
    Mar 16 at 21:18

13 Answers 13

596

You are using the --noImplicitAny and TypeScript doesn't know about the type of the Users object. In this case, you need to explicitly define the user type.

Change this line:

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

to this:

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

Or define the type of your Users object:

//...
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');
//...
5
  • 101
    In your tsconfig.json add this "noImplicitAny": false to "compilerOptions":{} it will work Jan 16, 2018 at 7:19
  • 12
    @naval-kishor-jha , but noImplicitAny is a good option , we have to find a solution with noImplicitAny as true , is that a Typescript issue ? Dec 17, 2018 at 10:37
  • 6
    Sometimes, I encounter this problem then I quickly search on StackOverflow, I see my vote to you, every time I'm mad at myself for this problem :) I hope so, I will never see this page Aug 8, 2019 at 7:32
  • 16
    Disabling noImplicitAny without understanding the implications of doing so is a bad decision and it should not be recommended without additional explanation. It should only be disabled if you're migrating from a type-loose codebase and as a short-term measure. Disabling it will reduce compiler errors, but some of those are hinting at actual bugs in your code; those bugs are still present but now invisible. Consider that noImplicitAny: true doesn't mean you can't use any. It means you have to do it with consideration. It only takes a few moments to type : any.
    – Mark
    Feb 18, 2022 at 13:29
  • If you change your import to an import instead of require, Typescript will infer the type of the JSON object as if you defined it inline. You won't have an implicit any, and you won't have to define any special interfaces that you blindly hope will match the shape of the JSON object. It's very good. It's possible this was a more recent addition to Typescript, I don't know when it started doing this.
    – Vectorjohn
    May 24, 2022 at 17:46
201

In your tsconfig.json file set the parameter "noImplicitAny": false under compilerOptions to get rid of this error.

2
  • 105
    Careful. This workaround silences the error and only fixes the symptom; it doesn't fix the root cause.
    – jbmusso
    May 29, 2019 at 9:31
  • 6
    @jbmusso is right. Try to use the strict mode instead of shutting it down. This way you won't find errors at runtime
    – Ionel Lupu
    Jul 14, 2019 at 7:35
50

Make these changes in your compilerOptions section of tsconfig.json file this worked for me

"noImplicitAny": false

no need to set

"strict":false

And please wait 1 or two minutes compilation is very slow some pcs

4
  • 20
    this solution turns off a major benefit of TypeScript, which is type checking. In my opinion this solution should be avoided. Apr 13, 2022 at 17:29
  • 4
    Applying this solution means death of typescript. Avoid it. May 31, 2022 at 11:28
  • to use some of typescript(better than nothing) instead of going full 100% typescript, this flag is very useful and much less noisy to me.
    – Shawn Shaw
    Aug 3 at 16:07
  • This is a duplicate answer of @st_ahmed's 3 years after...
    – icc97
    Sep 23 at 15:16
20

I found this issue in Angular to arguments of function.

Before my code giving error

Parameter 'event' implicitly has an 'any' type

Here Is code

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

Here is the change, after the argument write : any and the error is solved

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

Working fine for me.

15

if you get an error as Parameter 'element' implicitly has an 'any' type.Vetur(7006) in vueJs

with the error:

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

you can fixed it by defining thoes variables as any as follow.

corrected code:

exportColumns.forEach((element: any) => {
      if (element.command !== undefined) {
        let d = element.command.findIndex((x: any) => x.name === "destroy");
1
  • 1
    This was exactly what I needed, thanks. The 'element' of the ForEach needed surrounding in parenthesis before it could have a type assigned to it. i.e. .forEach((element: object)...
    – CodeThief
    Mar 25, 2020 at 15:00
6

Minimal error reproduction

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)

Recommended solution: --resolveJsonModule

The simplest way for your case is to use --resolveJsonModule compiler option:
import users from "./data.json" // `import` instead of `require`
const foundUser = users.find(user => user.id === 42); // user is strongly typed, no `any`!

There are some alternatives for other cases than static JSON import.

Option 1: Explicit user type (simple, no checks)

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

Option 2: Type guards (middleground)

Type guards are a good middleground between simplicity and strong types:
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)
}
You can even switch to assertion functions (TS 3.7+) to get rid of if and throw an error instead.
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

Option 3: Runtime type system library (sophisticated)

A runtime type check library like io-ts or ts-runtime can be integrated for more complex cases.


Not recommended solutions

noImplicitAny: false undermines many useful checks of the type system:
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)

Also better provide an explicit User type for user. This will avoid propagating any to inner layer types. Instead typing and validating is kept in the JSON processing code of the outer API layer.

4

go to tsconfig.json and comment the line the //strict:true this worked for me

4

My case:


export default function ({user, path}) {
    return (
        //...
    )
}

I changed to

export default function ({user, path} : {
    user: string
    path: string
}) {
    return (
        //...
    )
}

3

I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.

1
  • 13
    Setting strict mode to false is very bad. You won't get errors on compile time anymore but you will get them at runtime, which you don't want. I highly recommend setting the strict mode to true
    – Ionel Lupu
    Jul 14, 2019 at 7:35
1

try to declare the type of user. Such as

let user:Object = {sample object}

Follow this methid. As

let var:type = val
1

Or add the below on top of the code that has the error

// @ts-ignore: Object is possibly 'null'.
0

Parameter 'post' implicitly has an 'any' type in Angularcli Perhaps on project creation you've enabled Angular's strict mode in your app? Max recommends to disable strict mode If you've enabled strict mode, please disable it for this course by setting the strict property in tsconfig.json to false

-4

Just add "checkJs": false into jsconfig.json file