From 382ccab624fc18cac92058bc092f5c83bfe94bb1 Mon Sep 17 00:00:00 2001 From: edvardchen <> Date: Thu, 11 Jul 2019 11:33:32 +0800 Subject: [PATCH] feat: more TS supports --- lib/rules/no-literal-string.js | 40 ++++++++++++++++++---------- tests/lib/rules/no-literal-string.js | 14 +++++++++- 2 files changed, 39 insertions(+), 15 deletions(-) diff --git a/lib/rules/no-literal-string.js b/lib/rules/no-literal-string.js index a7c8c6c..e4d2c74 100644 --- a/lib/rules/no-literal-string.js +++ b/lib/rules/no-literal-string.js @@ -179,20 +179,6 @@ module.exports = { // name if key is Identifier; value if key is Literal // dont care whether if this is computed or not if (isUpperCase(parent.key.name || parent.key.value)) visited.add(node); - - // - // TYPESCRIPT PART - // - - if (typeChecker) { - const tsNode = esTreeNodeToTSNodeMap.get(node); - const typeObj = typeChecker.getTypeAtLocation(tsNode.parent); - - if (typeObj.isStringLiteral()) { - visited.add(node); - } - // • • • • • - } }, 'CallExpression Literal'(node) { @@ -212,6 +198,32 @@ module.exports = { if (isUpperCase(trimed)) return; if (match(trimed)) return; + + // + // TYPESCRIPT + // + + if (typeChecker) { + const tsNode = esTreeNodeToTSNodeMap.get(node); + const typeObj = typeChecker.getTypeAtLocation(tsNode.parent); + + // var a: 'abc' = 'abc' + if (typeObj.isStringLiteral()) { + return; + } + + // var a: 'abc' | 'name' = 'abc' + if (typeObj.isUnion()) { + const found = typeObj.types.some(item => { + if (item.isStringLiteral() && item.value === node.value) { + return true; + } + }); + if (found) return; + } + } + // • • • • • + context.report({ node, message }); } }; diff --git a/tests/lib/rules/no-literal-string.js b/tests/lib/rules/no-literal-string.js index 31a1cc8..17784b5 100644 --- a/tests/lib/rules/no-literal-string.js +++ b/tests/lib/rules/no-literal-string.js @@ -110,7 +110,11 @@ tsTester.run('no-literal-string', rule, { { code: '
', filename: 'a.tsx' }, { code: "var a: Element['nodeName']" }, { code: "var a: Omit