-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #28 from criteo/no-indexed-access-on-enums
Add 'No indexed access on enums' rule
- Loading branch information
Showing
3 changed files
with
58 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
/** | ||
* @fileoverview no-indexed-access-on-enums | ||
* @author Connor Ullman | ||
* @author Adam Perea | ||
*/ | ||
'use strict'; | ||
|
||
module.exports = { | ||
meta: { | ||
type: 'suggestion', | ||
docs: { | ||
description: 'Do not use indexed access on enums', | ||
recommended: 'error', | ||
}, | ||
messages: { | ||
failure: 'Indexed accesses on an enum are almost always a mistake, as the names of the enum values should not be "data" in the context of the application at runtime.', | ||
}, | ||
schema: [], | ||
}, | ||
|
||
create(context) { | ||
return { | ||
MemberExpression(node) { | ||
const parserServices = context.parserServices; | ||
if (!parserServices) return; | ||
|
||
const checker = parserServices.program?.getTypeChecker(); | ||
if (!checker) return; | ||
|
||
if (!node.computed) return; | ||
|
||
const objectNode = parserServices.esTreeNodeToTSNodeMap.get(node.object); | ||
const objectSymbol = checker.getSymbolAtLocation(objectNode); | ||
if (!objectSymbol) return; | ||
|
||
const enumSymbol = | ||
ts.SymbolFlags.Alias & objectSymbol.flags ? checker.getAliasedSymbol(objectSymbol) : objectSymbol; | ||
const isEnum = ts.SymbolFlags.Enum & enumSymbol.flags; | ||
if (!isEnum) return; | ||
|
||
context.report({ | ||
node, | ||
messageId: 'failure', | ||
}); | ||
}, | ||
}; | ||
}, | ||
}; |