New eslint errors with the @typescript-eslint/no-unsafe-* rules

nerdlinger picture nerdlinger · Jun 11, 2020 · Viewed 9.1k times · Source

I'm having some trouble with adding them into some existing projects. For example, I have a class in a module that I developed:

export default class ClassName {
  // Class members
}

Now I import that into another project:

import ClassName from 'modulename';

const object = new ClassName();

I get 2 errors on this line.

On the object in const object:

error  Unsafe assignment of an any value                @typescript-eslint/no-unsafe-assignment

On the new in new ClassName:

error  Unsafe construction of an any type value         @typescript-eslint/no-unsafe-call

How can I avoid these errors?! I would really like to be able to follow these rules because I think they'd be so useful!

Thanks.


Here's another example:

import { readJsonSync } from 'fs-extra';
const testEnv = readJsonSync(testEnvPath);

Here I get the no-unsafe-assignment error on the testEnv of const testEnv, and the no-unsafe-call error on the readJsonSync call on the second line.

I can get rid of the first one with this code:

interface ITestEnv {
  // interface members
}
const testEnv: ITestEnv = readJsonSync(testEnvPath) as ITestEnv;

however, I still can't figure out how to get rid of the second one on the readJsonSync call.

Answer

Marco L. Abreu picture Marco L. Abreu · Jun 11, 2020

In the first case, you have just one error coming from the constructor, which is cascading to the const assignment. Something in your class implementation is making the type-inference to be inferred as any.

Not saying your code is incorrect. It might be, but there's an (open issue on Github) reporting a constructor as being incorrectly flagged by the same rule.

On your second issue, have you added @type/fs-extra as a project dependency? Many npm packages do not have types themselves. Types are created by someone and added to the @types library. When that's the case, the @types/package_name must be added as a dependency separately.