[英]How to avoid triggering eslint's for..in when using Typescript
I currently use the TypeScript recommended approach to iterate over object's keys., like this:我目前使用 TypeScript 推荐的方法来迭代对象的键。像这样:
let key: keyof ExampleObject;
for (key in exampleObject) {
// do some work with exampleObject[key];
}
In my current project Eslint complains about using for..in
construct like this:在我当前的项目中,Eslint 抱怨使用
for..in
构造如下:
for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array no-restricted-syntax
The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype guard-for-in
I have seen several similar questions and answers for JavaScript eg using Object.keys(...) but TypeScript doesn't like this approach too and it loses some of the typesafety.我已经看到 JavaScript 的几个类似问题和答案,例如使用 Object.keys(...) 但 TypeScript 也不喜欢这种方法,它失去了一些类型安全性。
Is there a way to avoid triggering Eslint rules while still adhering to the TypeScript best practices?有没有办法避免触发 Eslint 规则,同时仍然遵守 TypeScript 最佳实践? I know I can just turn off the designated rules but I hope there is a less 'hacky' way
我知道我可以关闭指定的规则,但我希望有一种不那么“hacky”的方式
Eslint is complaining for an extremely valid reason, and you should basically never use for...in
unless you explicitly want to walk the prototype chain, which you basically never do. Eslint 的抱怨有一个非常正当的理由,你基本上不应该使用
for...in
除非你明确想要遍历原型链,而你基本上从来没有这样做过。
As for the rest...至于rest……
TypeScript doesn't like this approach too and it loses some of the typesafety.
TypeScript 也不喜欢这种方法,它失去了一些类型安全性。
Yeah.是的。 Your problem isn't
Object.keys
, your problem is that runtime reflection and compile-time type safety are natural enemies in the wild.你的问题不是
Object.keys
,你的问题是运行时反射和编译时类型安全是天敌。 So there isn't a 'clean' way to do this, you are saying "give me all of the properties of this object at runtime" which can't be safely known at compile-time, and changing the mechanism by which you ask for that isn't going to fix the fundamental underlying issue.所以没有一个“干净”的方法来做到这一点,你说“在运行时给我这个 object 的所有属性”,这在编译时不能安全地知道,并改变你问的机制因为那不会解决根本的潜在问题。
You have a few options for dealing with this.您有几种选择来处理这个问题。
instanceof
, typeof
, the in
operator, etc to narrow the type.instanceof
、 typeof
、 in
运算符等来缩小类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.