When counting user-created data it can be useful to create an object with no prototype using Object.create(null) so that the user data does not conflict with prototype property names. Such an object does not need to be filtered with an if statement when iterating over it because by design there are no properties on the prototype chain to filter out.
3.10.21.8.10[email protected]const countData = (data) => {
let output = '',
count = Object.create(null) as any;
for (let i = 0; i < data.length; i++) {
if (typeof count[data[i]] === 'undefined') {
count[data[i]] = 1;
}
else {
count[data[i]]++;
}
}
for (let name in count) {
output += `${name}: ${count[name]}\n`;
}
return output;
};
countData(['a', 'a', 'b', 'c', 'a', 'b']);
/*
Logs:
"a: 3
b: 2
c: 1
"
*/
(If you remove "as any" you can run this in the console in Chrome to check it.)
tslint.json configuration:
{
"rules": {
"forin": true,
}
}
>> test.ts[12, 5]: for (... in ...) statements must be filtered with an if statement
No error
Hi Isaac! :)
This kind of semantic analysis to determine if a value has no prototype is not really feasible because we don't do full-program analysis (blocked on #680). In my projects I generally discourage for-in in favor of Object.keys() -- hopefully that's an acceptable workaround for you?
Hey Adi :)
In my projects I generally discourage for-in in favor of Object.keys() -- hopefully that's an acceptable workaround for you?
My workaround is to disable the rule ๐ But yeah, Object.keys() is probably fine in most cases.
I used for (const key in Object.keys(object)) { after getting the forin error at various places.
I again ran ng lint and got the same error in some places.
Please explain what I am doing wrong?
I have disabled the rule as of now.
Object.entries(object).forEach( ([key, value]) => {
doSomeThing(key, value);
});
No longer blocked on #680's type checking, but still unclear if we want this.
โ ๏ธ TSLint's time has come! โ ๏ธ
TSLint is no longer accepting most feature requests per #4534. See typescript-eslint.io for the new, shiny way to lint your TypeScript code with ESLint. โจ
It was a pleasure open sourcing with you all!
๐ค Beep boop! ๐ TSLint is deprecated ๐ _(#4534)_ and you should switch to typescript-eslint! ๐ค
๐ This issue is being locked to prevent further unnecessary discussions. Thank you! ๐
Most helpful comment
Hi Isaac! :)
This kind of semantic analysis to determine if a value has no prototype is not really feasible because we don't do full-program analysis (blocked on #680). In my projects I generally discourage for-in in favor of
Object.keys()-- hopefully that's an acceptable workaround for you?