Last active
January 29, 2023 17:45
-
-
Save Dremora/0bff8d6a65fff8443282b97322f0da64 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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