简体   繁体   中英

How to prevent the call to a property or method on an any variable

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.

TypeScript ESLint Playground link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM