简体   繁体   English

如何防止调用任何变量的属性或方法

[英]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?在具有 typescript 的 NodeJs 项目中,如果我有任何变量,是否有办法使用 typescript 编译或 eslint 或其他方法来防止从该变量调用未识别的属性或方法?

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 编译器设置来执行此操作,因为any类型的全部意义在于关闭类型检查并允许各种可能不安全的操作。 TypeScript's viewpoint is that you shouldn't use any in this circumstance. TypeScript 的观点是你不应该在这种情况下使用any

Fortunately for your use case, there is a @typescript-eslint/no-unsafe-member-access ESLint rule which behaves this way:幸运的是,对于您的用例,有一个@typescript-eslint/no-unsafe-member-access ESLint 规则,其行为如下:

This rule disallows member access on any variable that is typed as any .此规则不允许成员访问类型为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 TypeScript ESLint 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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