UNPKG

@masknet/eslint-plugin

Version:
51 lines 1.96 kB
import { isIdentifierName, isLiteralValue } from '../../node.js'; import { createRule, ensureParserWithTypeInformation } from '../../rule.js'; export default createRule({ name: 'string/no-unneeded-to-string', meta: { type: 'suggestion', fixable: 'code', docs: { description: 'Disallow `String#toString()` when simpler alternatives exist', recommended: 'stylistic', requiresTypeChecking: true, }, schema: [], messages: { invalid: 'Disallow use `.toString()` in string', }, }, create(context) { ensureParserWithTypeInformation(context.sourceCode.parserServices); const { program, esTreeNodeToTSNodeMap } = context.sourceCode.parserServices; const typeChecker = program.getTypeChecker(); return { CallExpression(node) { if (node.callee.type !== 'MemberExpression') return; const { object, property } = node.callee; if (!isIdentifierName(property, 'toString') && !isLiteralValue(property, 'toString')) return; if (!isStringPrimitive(typeChecker, esTreeNodeToTSNodeMap.get(object))) return; context.report({ node: property, messageId: 'invalid', fix(fixer) { return fixer.replaceText(node, context.sourceCode.getText(object)); }, }); }, }; }, }); function isStringPrimitive(checker, node) { const type = checker.getTypeAtLocation(node); if (type.isStringLiteral()) return true; if (checker.typeToString(type) === 'string') return true; const symbol = type.getSymbol(); return symbol && checker.symbolToString(symbol) === 'String'; } //# sourceMappingURL=no-unneeded-to-string.js.map