How to bypass warning Unexpected any. Specify a different type @typescript-eslint/no-explicit-any

Viewed 46645

We have a strict zero lint issues policy. This means all errors and warnings need to be fixed.

Facing this lint error in our React typescript project:

warning Unexpected any. Specify a different type @typescript-eslint/no-explicit-any

Searched on Google and on the lint website. I didn't find a solution as such!

Tried this: // eslint:@typescript-eslint/no-explicit-any: "off" which is not working

Does anyone know how to bypass this eslint rule in a React typescript project?

7 Answers

Something that works for me when trying to bypass the same rule, specially for overloading methods is to use: // eslint-disable-next-line if you can simply just add a comment right above the line with the issue.

Or you can ignore the rule for just a section of the code by /* eslint-disable rule-name */ your-block-of-code /* eslint-enable rule-name */ The comments here must be block comments.

In Angular we add that in the TypeScript rules. Not in the general rules because sometimes that doesn't work.

Example:

"rules": {
             
   "@typescript-eslint/no-explicit-any": ["off"]
}

In the .eslintrc.json file

Can you use unknown? e.g. HttpResponse<unknown>

Following will work for you.

/* eslint-disable @typescript-eslint/no-explicit-any */

Check eslint documentation

"@typescript-eslint/no-explicit-any": ["off"]

As described by typescript-eslint:

  • If you want a type meaning "any object", you probably want Record<string, unknown> instead.
  • If you want a type meaning "any value", you probably want unknown instead

In fact you can often replace any with a better option. For that you can use Record type as mentioned by @RollingInTheDeep or you can use index signature like:

{[prop: string]: number | unknown} // object.x = number | unknown
{[prop: string]: {[prop:string]: number | undefined}} | boolean // object.x can be a boolean or another object that contains key strings with numeric or undefined values

One option that can avoid the use of unknown and bring greater readability is to apply generics in case of functions where any is part of the parameter and the return. This for example declares a type and returns a list of the same

export function getObjectValues<T>(objects: {
[prop: string]: T[] }): T[] { . . .  } 

If your expecting (key, value) pairs in an object, but dont know what the keys may be you can define a type as below. Where someObject is unknown, but instead of using any use the Record<string, unknown> eslint is fine with this.

    type MyType = {
        name: string;
        someObject: Record<string, unknown>;
     }
Related