Skip to content

Instantly share code, notes, and snippets.

@Dremora
Last active January 29, 2023 17:45
Show Gist options
  • Save Dremora/0bff8d6a65fff8443282b97322f0da64 to your computer and use it in GitHub Desktop.
Save Dremora/0bff8d6a65fff8443282b97322f0da64 to your computer and use it in GitHub Desktop.
import { ESLintUtils, TSESTree } from '@typescript-eslint/utils';
import * as tsutils from 'tsutils';
import * as ts from 'typescript';
export const rule = ESLintUtils.RuleCreator.withoutDocs({
meta: {
docs: {
description: 'ban date comparison using ==, ===, !=, !==',
recommended: 'warn',
},
schema: [],
messages: {
unexpected:
'Use `date.getTime()` instead to compare timestamps using < or >.',
},
type: 'problem',
},
defaultOptions: [],
create(context) {
const { esTreeNodeToTSNodeMap, program } =
ESLintUtils.getParserServices(context);
const checker = program.getTypeChecker();
function isDate(node: TSESTree.Node): boolean {
const tsNode = esTreeNodeToTSNodeMap.get(node);
const type = checker.getTypeAtLocation(tsNode);
return (
tsutils.isTypeFlagSet(type, ts.TypeFlags.Object) &&
type.symbol.name === 'Date'
);
}
return {
BinaryExpression: (node) => {
if (
node.operator === '==' ||
node.operator === '===' ||
node.operator === '!=' ||
node.operator === '!=='
) {
if (isDate(node.left) && isDate(node.right)) {
context.report({
node,
messageId: 'unexpected',
});
}
}
},
};
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment