Skip to content

Commit

Permalink
feat: more TS supports
Browse files Browse the repository at this point in the history
  • Loading branch information
edvardchen committed Jul 11, 2019
1 parent 2af8b08 commit 382ccab
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 15 deletions.
40 changes: 26 additions & 14 deletions lib/rules/no-literal-string.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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 });
}
};
Expand Down
14 changes: 13 additions & 1 deletion tests/lib/rules/no-literal-string.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,11 @@ tsTester.run('no-literal-string', rule, {
{ code: '<div className="hello"></div>', filename: 'a.tsx' },
{ code: "var a: Element['nodeName']" },
{ code: "var a: Omit<T, 'af'>" },
{ code: "type T = {name: 'b'} ; var a: T = {name: 'b'}" }
{ code: `var a: 'abc' = 'abc'` },
{ code: `var a: 'abc' | 'name' | undefined= 'abc'` },
{ code: "type T = {name: 'b'} ; var a: T = {name: 'b'}" },
{ code: "function Button({ t= 'name' }: {t: 'name'}){} " },
{ code: "type T ={t?:'name'|'abc'};function Button({t='name'}:T){}" }
],
invalid: [
{
Expand All @@ -119,6 +123,14 @@ tsTester.run('no-literal-string', rule, {
errors
},

{
code: "function Button({ t= 'name' }: {t: 'name' & 'abc'}){} ",
errors
},
{
code: "function Button({ t= 'name' }: {t: 1 | 'abc'}){} ",
errors
},
{ code: "var a: {type: string} = {type: 'bb'}", errors }
]
});
Expand Down

0 comments on commit 382ccab

Please sign in to comment.