after some research, I couldn't find an answer to this problem :
In a NodeJs project with typescript, if I have an any variable, is there a way to prevent the call to an unidentified property or method from this variable either using typescript compilation or eslint or something else ?
Here is an exemple:
let test: any;
console.log( test.unknownProperty ); // Should not pass
There's no TypeScript compiler setting to do this, since the whole point of the any
type is to turn off type checking and allow all sorts of potentially unsafe operations. TypeScript's viewpoint is that you shouldn't use any
in this circumstance.
Fortunately for your use case, there is a @typescript-eslint/no-unsafe-member-access
ESLint rule which behaves this way:
This rule disallows member access on any variable that is typed as
any
.
Let's test it out:
let test: any;
console.log(test.unknownProperty); // error!
// -------> ~~~~~~~~~~~~~~~~~~~~
// Unsafe member access .unknownProperty on an `any` value.
Looks good.