Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 672
nerdlinger Avatar asked Jun 11 '20 14:06

nerdlinger


2 Answers

ESlint can not resolve the absolute import of your module,
which makes it to infer your class type as any.

Make sure baseUrl and paths in tsconfig.json file used by ESlint are defined correctly.

@see Typescript – Module Resolution

like image 171
am0wa Avatar answered Oct 07 '22 23:10

am0wa


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.

like image 37
Marco L. Abreu Avatar answered Oct 07 '22 23:10

Marco L. Abreu