From b1dcadbcac49f0d5b439b041723e701d1347c2d6 Mon Sep 17 00:00:00 2001 From: Edvard Chen Date: Mon, 15 Jul 2024 08:31:08 +0800 Subject: [PATCH] feat: ignore hand-written literal type --- lib/rules/no-literal-string.js | 29 ++++++++++++++++++++++++++ tests/lib/fixtures/valid-typescript.ts | 7 +++++++ 2 files changed, 36 insertions(+) diff --git a/lib/rules/no-literal-string.js b/lib/rules/no-literal-string.js index 057dd24..3565176 100644 --- a/lib/rules/no-literal-string.js +++ b/lib/rules/no-literal-string.js @@ -89,10 +89,39 @@ module.exports = { }); } + const { esTreeNodeToTSNodeMap, program } = parserServices; + let typeChecker; + if (program && esTreeNodeToTSNodeMap) + typeChecker = program.getTypeChecker(); + function validateBeforeReport(node) { if (isValidScope()) return; if (isValidLiteral(options, node)) return; + // ─── Typescript ────────────────────────────────────── + + if (typeChecker) { + const tsNode = esTreeNodeToTSNodeMap.get(node); + const typeObj = typeChecker.getContextualType(tsNode); + if (typeObj) { + // 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; + } + } + } + // ───────────────────────────────────────────────────── + report(node); } diff --git a/tests/lib/fixtures/valid-typescript.ts b/tests/lib/fixtures/valid-typescript.ts index 552d691..4821c3b 100644 --- a/tests/lib/fixtures/valid-typescript.ts +++ b/tests/lib/fixtures/valid-typescript.ts @@ -18,4 +18,11 @@ var a6 = T2['howard']; function Button2({ t = 'name' }: { t: 'name' }) {} type Ta = { t?: 'name' | 'abc' }; +let ta: Ta = { t: 'abc' }; + +const str: 'str' = 'str'; + +type Animal = 'dog' | 'cat'; +const animal: Animal = 'dog'; + function Button3({ t = 'name' }: Ta) {}