Skip to content

Instantly share code, notes, and snippets.

@mhabedinpour
Created March 5, 2023 19:11
Show Gist options
  • Save mhabedinpour/99f7661225f0010a05b22645c5ed51b2 to your computer and use it in GitHub Desktop.
Save mhabedinpour/99f7661225f0010a05b22645c5ed51b2 to your computer and use it in GitHub Desktop.
/* eslint-disable */
const {ESLintUtils} = require('@typescript-eslint/experimental-utils');
const TS = require('typescript');
const TSUtils = require('tsutils');
module.exports = ESLintUtils.RuleCreator.withoutDocs({
meta: {
type: 'problem',
docs: {
description: 'Bans using binary operators on string types'
},
messages: {
noStringOperator: 'Do not use binary operators on string types.'
}
},
defaultOptions: [],
create: (context) => {
return {
BinaryExpression: (node) => {
if (node.operator === '===' || node.operator === '==' || node.operator === '!==' || node.operator === '!=') {
return;
}
const parserServices = ESLintUtils.getParserServices(context);
const checker = parserServices.program.getTypeChecker();
const originalRightNode = parserServices.esTreeNodeToTSNodeMap.get(node.right);
const originalLeftNode = parserServices.esTreeNodeToTSNodeMap.get(node.left);
const rightNodeType = checker.getTypeAtLocation(originalRightNode);
const leftNodeType = checker.getTypeAtLocation(originalLeftNode);
if (TSUtils.isTypeFlagSet(rightNodeType, TS.TypeFlags.StringLike) || TSUtils.isTypeFlagSet(leftNodeType, TS.TypeFlags.StringLike)) {
context.report({
messageId: 'noStringOperator',
node: node.right
});
}
}
};
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment